Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why AbstractCollection does not implement equals()?

Did you know that :

Map<Object,Object> m1 = new HashMap<Object, Object>();
Map<Object,Object> m2 = new HashMap<Object, Object>();
System.out.println("m1.equals(m2) = "+m1.equals(m2));
System.out.println("m1.keySet().equals(m2.keySet()) = "
            +m1.keySet().equals(m2.keySet()));
System.out.println("m1.entrySet().equals(m2.entrySet()) = "
            +m1.entrySet().equals(m2.entrySet()));
System.out.println("m1.values().equals(m2.values()) = "
            +m1.values().equals(m2.values()));

would output :

m1.equals(m2) = true
m1.keySet().equals(m2.keySet()) = true
m1.entrySet().equals(m2.entrySet()) = true
m1.values().equals(m2.values()) = false

This is caused by the fact that AbstractCollection (which HashMap$Values inherits from) does not overrides #equals().

Do you have an idea why this is so ?

like image 557
Michel Avatar asked Dec 04 '08 17:12

Michel


2 Answers

Per the contract of Collection#equals(), there is no general-purpose equals() methods for Collections, and thus AbstractCollection cannot provide one.

Note that HashMap$Values is neither a Set nor a List, thus the quandary and in a sense the reason it does not support equals().

like image 99
Greg Case Avatar answered Nov 11 '22 01:11

Greg Case


Both AbstractList and AbstractSet extend AbstractCollection, and they have different behaviors for their equals() methods, specified by the interfaces List and Set. The interface for Collection says:

While the Collection interface adds no stipulations to the general contract for the Object.equals, programmers who implement the Collection interface "directly" (in other words, create a class that is a Collection but is not a Set or a List) must exercise care if they choose to override the Object.equals.

So AbstractCollection should definitely not override equals(). That said, I don't really know why HashMap$Values would not implement equals() itself.

like image 4
Craig P. Motlin Avatar answered Nov 11 '22 00:11

Craig P. Motlin