Java HashMap not finding key, but it should

后端 未结 4 1920
隐瞒了意图╮
隐瞒了意图╮ 2020-12-18 08:17

I have a strange issue occuring in my application, I will quickly explain global architecture and then my problem in depth.

I use a service to populate a HashM

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-18 08:25

    [This basically expands on Jesper's answer but the details may help you]

    Since recreating the map using new HashMap(map) is able to find the element I am suspecting that the hashCode() of the DomainObject changed after adding it to the Map.

    For example if your DomainObject looks the following

    class DomainObject {
        public String name;
        long hashCode() { return name.hashCode(); }
        boolean equals(Object other) { /* compare name in the two */'
    }
    

    Then

       Map m = new HashMap();
       DomainObject do = new DomainObject(); 
       do.name = "ABC";
       m.put(do, true); // do goes in the map with hashCode of ABC
       do.name = "DEF";
       m.get(do); 
    

    The last statement above will return null. Because the do object you have inside the map is under the bucket of "ABC".hashCode(); there is nothing in the "DEF".hashCode() bucket.

    The hashCode of the Objects in map should not change once added to map. The best way to ensure it is that the fields on which hashCode depends must be immutable.

提交回复
热议问题