Equality between 2 HashMap

后端 未结 4 2167
醉话见心
醉话见心 2020-12-15 17:33

In the equals() method of my class, I am using a private instance HashMap variable to compare for the equality. However, 2 different objects still show being equal when comp

4条回答
  •  既然无缘
    2020-12-15 18:40

    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:

    1. 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.
    2. 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.

提交回复
热议问题