The equals
method on a Java array type is equivalent to ==
, because Java array "classes" do not override Object.equals
.
If you want to compare arrays "by value" you need to either use the appropriate java.util.Arrays.equals(...)
method, or implement it yourself.
If your HashMap
uses arrays as keys or values, then it is going to call the array's equals
method to test if the keys and/or values are the same between two maps. This would make HashMap.equals
behave strangely (from your perspective). That is what the linked article is saying. However, array semantic only affect HashMap
equality if you use arrays as the key or value classes. If you don't, then HashMap::equals
should just work as expected.
The javadocs for equality on Map
classes are a bit involved, but they basically boil down to taking the two entry sets, comparing their sizes, and then doing s1.containsAll(s2)
. Of course, this is expensive, but it should work for all of the Map
classes that correctly implement the Map
interface.
Note that using arrays as keys for maps is a bad idea for a couple of reasons:
- The semantics of array
equals
and hashCode
are wrong for a HashMap
in most scenarios. For most use-cases, you need the map to compare the keys by value not by object identity.
- Arrays are mutable. If we assumed that there was a workaround for the
equals
/ hashcode
problem, you could still break a map's invariants by modifying an array key.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…