Why is my HashMap allowing duplicate keys?

前端 未结 1 403
庸人自扰
庸人自扰 2021-01-13 03:12

Hey I\'m using a HashMap to keep track of services and service-requests on a BulletinBoard. However, I must have the hashcode and equals wrong because I\'m gett

1条回答
  •  离开以前
    2021-01-13 03:12

    The likeliest reason is that the objects you use as keys are mutable. So if you do something like:

    map.put(anAdvert, 1);
    anAdvert.spawn(); //modifies id, which affects hashcode and equals
    

    The behaviour of the map will be unexpected.

    cf Map's javadoc

    Note: great care must be exercised if mutable objects are used as map keys. The behavior of a map is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is a key in the map.

    0 讨论(0)
提交回复
热议问题