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 ?
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().
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With