What happens to the lookup in a Hashmap or Hashset when the objects Hashcode changes

后端 未结 4 476
太阳男子
太阳男子 2021-01-04 10:00

In a Hashmap the hash code of the key provided is used to place the value in the hashtable. In a Hashset the obects hashcode is used to place the value in the underlying has

4条回答
  •  长发绾君心
    2021-01-04 11:00

    In your example, the keys are String which are immutable. So the hashcode of the keys won't change. What happens when the hashcode of the keys changes is undefined and leads to "weird" behaviour. See the example below, which prints 1, false and 2. The object remains in the set, but the set looks like it is broken (contains returns false).

    Extract from Set's javadoc:

    Note: Great care must be exercised if mutable objects are used as set elements. The behavior of a set is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is an element in the set. A special case of this prohibition is that it is not permissible for a set to contain itself as an element.

    public static void main(String args[]) {
        Set set = new HashSet<>();
        MyObject o1 = new MyObject(1);
        set.add(o1);
        o1.i = 2;
        System.out.println(set.size());       //1
        System.out.println(set.contains(o1)); //false
        for (MyObject o : set) {
            System.out.println(o.i);          //2
        }
    }
    
    private static class MyObject {
        private int i;
    
        public MyObject(int i) {
            this.i = i;
        }
    
        @Override
        public int hashCode() {
            return i;
        }
    
        @Override
        public boolean equals(Object obj) {
            if (obj == null) return false;
            if (getClass() != obj.getClass()) return false;
            final MyObject other = (MyObject) obj;
            if (this.i != other.i) return false;
            return true;
        }
    }
    

提交回复
热议问题