Why should I override hashCode() when I override equals() method?

后端 未结 5 2107
夕颜
夕颜 2020-11-27 05:22

Ok, I have heard from many places and sources that whenever I override the equals() method, I need to override the hashCode() method as well. But consider the following piec

5条回答
  •  野性不改
    2020-11-27 06:17

    Most of the other comments already gave you the answer: you need to do it because there are collections (ie: HashSet, HashMap) that uses hashCode as an optimization to "index" object instances, an those optimizations expects that if: a.equals(b) ==> a.hashCode() == b.hashCode() (NOTE that the inverse doesn't hold).

    But as an additional information you can do this exercise:

    class Box {
         private String value;
         /* some boring setters and getters for value */
         public int hashCode() { return value.hashCode(); }
         public boolean equals(Object obj) { 
               if (obj != null && getClass().equals(obj.getClass()) { 
                   return ((Box) obj).value.equals(value); 
                } else { return false; }
         }
    }
    

    The do this:

    Set s = new HashSet();
    Box b = new Box();
    b.setValue("hello");
    s.add(b);
    s.contains(b); // TRUE
    b.setValue("other");
    s.contains(b); // FALSE
    s.iterator().next() == b // TRUE!!! b is in s but contains(b) returns false
    

    What you learn from this example is that implementing equals or hashCode with properties that can be changed (mutable) is a really bad idea.

提交回复
热议问题