Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are two empty ArrayLists with different generic types equal?

I have a doubt regarding how equals() method works for ArrayList. The below code snippet prints true.

ArrayList<String> s = new ArrayList<String>();
ArrayList<Integer> s1 = new ArrayList<Integer>();
System.out.println(s1.equals(s));

Why does it print true?

like image 455
Amit Avatar asked Sep 10 '15 12:09

Amit


2 Answers

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.

like image 91
Suresh Atta Avatar answered Oct 03 '22 06:10

Suresh Atta


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 ==

like image 30
Adam Michalik Avatar answered Oct 03 '22 06:10

Adam Michalik