Probably the easiest way for any list would be:
listA.containsAll(listB) && listB.containsAll(listA)
Answer from user381105 on Stack OverflowProbably the easiest way for any list would be:
listA.containsAll(listB) && listB.containsAll(listA)
You could sort both lists using Collections.sort() and then use the equals method. A slighly better solution is to first check if they are the same length before ordering, if they are not, then they are not equal, then sort, then use equals. For example if you had two lists of Strings it would be something like:
public boolean equalLists(List<String> one, List<String> two){
if (one == null && two == null){
return true;
}
if((one == null && two != null)
|| one != null && two == null
|| one.size() != two.size()){
return false;
}
//to avoid messing the order of the lists we will use a copy
//as noted in comments by A. R. S.
one = new ArrayList<String>(one);
two = new ArrayList<String>(two);
Collections.sort(one);
Collections.sort(two);
return one.equals(two);
}
I'm trying to do my homework
I created two ArraLists of Integer, and the content in the list is as follows:
List1:
5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100 105 110 115 120 125 130 135 140 145 150
List2:
150 300 450 600 750
when i use
list1. get(list1. size() - 1) == list2. get(0);
I get false;
I have to use
list1.get(list1.size() - 1).equals(list2.get(0));
to get true;
Then I try the following code:
ArrayList<Integer> arrList1 = new ArrayList<Integer>();
ArrayList<Integer> arrList2 = new ArrayList<Integer>();
arrList1. add(10);
arrList2.add(10);
System.out.println(arrList1.get(0) == arrList2.get(0));
I get true;
I know that == can only be used to compare values, or Primitive types, while .equals() is used to compare references.
I'm sure what I'm storing in the ArrayList is integer, int, so why can't I use == for comparison? (And I'm also wondering why comparing 10 with == gets true and 150 gets false)
I wonder why this is happening?
Thanks in advance to everyone who helped me.