Why are two empty ArrayLists with different generic types equal?
Solution 1
Look the doc for the equals() method of ArrayList
Returns true if and only if the specified object is also a list, both lists have the same size, and all corresponding pairs of elements in the two lists are equal.
Since there are no elements, all the conditions satisfied and hence true
.
If you add elements to the both list (atleast one in each), to see the desired output.
Solution 2
The contract of the List.equals
is that two lists are equal if all their elements are equal (in terms of equals()
). Here, both are empty lists, so they are equal. The generic type is irrelevant, as there are anyway no list elements to compare.
However, they are not equal in terms of ==
as these are two different objects.
See this question for details between equals()
and ==
Solution 3
As previous answers pointed, equals returns true because both objects are instances of List
and have the same size (0).
It's also worth mentioning that the fact that one List
contains Integer
and the other String
does not affect the behaviour because of type erasure in Java.
Solution 4
Here is the ArrayList implementation of the equals method from the AbstractList with a few commments what it actually does:
public boolean equals(Object o) {
if (o == this) // Not the same list so no return
return true;
if (!(o instanceof List)) // is an instance of List, so no return
return false;
ListIterator<E> e1 = listIterator();
ListIterator<?> e2 = ((List<?>) o).listIterator();
while (e1.hasNext() && e2.hasNext()) { // Both have no next, so no loop here
E o1 = e1.next();
Object o2 = e2.next();
if (!(o1==null ? o2==null : o1.equals(o2)))
return false;
}
return !(e1.hasNext() || e2.hasNext()); // Both validate to false, so negating false return true in the end.
}
Comments
-
Amit over 2 years
I have a doubt regarding how
equals()
method works forArrayList
. The below code snippet printstrue
.ArrayList<String> s = new ArrayList<String>(); ArrayList<Integer> s1 = new ArrayList<Integer>(); System.out.println(s1.equals(s));
Why does it print
true
? -
Jeppe over 8 yearsIf the lists both had an element, set to null - how would the comparison then be? By value alone or type as well?
-
Suresh Atta over 8 years@JeppeRask
null
is equals tonull
:) -
HopefullyHelpful over 2 yearslinks don't seem to work