Equality between 2 HashMap

后端 未结 4 2175
醉话见心
醉话见心 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:24

    Native Java arrays don't have a .equals() function. So if your hashmap's values (or keys I suppose) are arrays, HashMap.equals() will fail. I suspect it'd fall back on Object.equals() which just checks to see if the two objects are actually the same object.

    // something like this
    class Object {
      public boolean equals( Object o) {
        return this == o;
      }
    }
    

    You can sidestep the problem by using some variant on a Container rather than an array[], as containers have their own .equals() which calls equals() on successive elements of the containers rather than simply checking if they're the same reference. The code for a Collection.equals implementation might look something like:

    public boolean equals(Object o) {
      // sets never equal lists and visa versa
      if (o instanceof MyCollectionSubclass) {
        Iterator myIterator = iterator();
        Iterator theirIterator = ((Collection)o).iterator();
        while (myIterator.hasNext() && theirIterator.hasNext()) {
          Object myObj = myIterator.next();
          Object theirObj = theirIterator.next();
          if (!myObj.equals(theirObj)) {
            return false;
          }
        }
        // at least one will be false or we wouldn't have left the above while loop
        return myIterator.hasNext() == theirIterator.hasNext();
      }
      // not our class
      return false;
    }
    

    This might produce a true value comparison depending on what the collection's contents do when you call their equals().

提交回复
热议问题