Changing an object which is used as a Map key

前端 未结 5 1520
醉话见心
醉话见心 2020-12-21 07:33

Let V be a class with a single attribute named K and its getter and setters.

What\'s supposed to happen if I do:

V v = new V();
v.setK(\"a\");
HashMa         


        
5条回答
  •  我在风中等你
    2020-12-21 07:41

    Quote from "Map" interface JavaDoc:

    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.

    You simply shouldn't mutate keys (in the way which changes their "hashCode"/"equals"). You will definitely have very long and awful debugging if you try.

    It's like you swap books in the library. Index became unreliable. You search for "Bradbury", but find "Simak".

提交回复
热议问题