Changing an object which is used as a Map key

前端 未结 5 1517
醉话见心
醉话见心 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:49

    The title of this question is misleading -- you are not changing the map key, as in mutating the object used as map key. When you say map.put(x, y), you are creating a map entry that aggregates two independent values: a key and a value. Where the key originates from is not seen by the map, it's just two objects. So, you have created a map entry ("a", v) and after that you just changed the state of v -- there is no way this could have influenced the map entry's key "a". If, on the other hand, you had an object K of your own making, like

    public class K { 
      private String s;
      public K(String s) { this.s = s; }
      public void setS(String s) { this.s = s; }
      public boolean equals(Object o) { return ((K)o).s.equals(this.s); }
      public int hashCode() { return s.hashCode(); }
    

    }

    and now you do

    final K k = new K("a");
    map.put(k, v);
    k.setS("b");
    map.get(k);
    

    then you would face the problem -- you mutated the object used as the map key.

提交回复
热议问题