This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
In the program above, list1 and list2 are compared using equals() in line 1 and line 2.
unless we override the equals() for comparing object references, equals() always returns false. As per the explanation equals() returns "false" in line 1 and line 3. But it returns "true" in line 2?
so does LinkedList or any Collection, overrides the equals() method of object?
Is the equals() method overridden by List, Set, Map ?
As line 4 returns false, equals() is not overridden by PriorityQueue?
Only Set, List and Map interfaces have a requirement to implement equals method in an elements-based way. In case of Collection it's not necessary and in a Queue it's even discouraged. That's what API for these types says.
Sets, Lists, and Maps do not necessarily override equals. LinkedList does because it is a subclass of AbstractList which overrides equals. However, we can not say anything in general about whether a implementation of a Collection does or does not override equals. You will have to check the javadoc for the particular implementation you are working with.
unless we override the equals() for comparing object references, equals() always returns false
This is not true. If you don't override equals, it will return true if and only if the two objects references point to the same object (the same address in memory).
Sreenivasa, you are right, the new documentation of List interface defines the behavior of equals method implemented by all List implementation more clearly
Compares the specified object with this list for equality. 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. (Two elements e1 and e2 are equal if (e1==null ? e2==null : e1.equals(e2)).) In other words, two lists are defined to be equal if they contain the same elements in the same order. This definition ensures that the equals method works properly across different implementations of the List interface.
So if you try this code, you'll get true as the answer