Changing an object which is used as a Map key

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

    V v = new V();
    v.setK("a");
    HashMap map = new HashMap();
    map.put(v.getk(),v);
    
    //Nothing will change in the hashmap with this step
    v.setK("b");
    

    but the problem will be while fetching the object V from map. If you call map.get(v.getk()), you will get null because the value in the map is mapped with object "a". However, since this String "a" is inter you can always fetch this object from map by map.get("a"); or

    V v = new V();
    v.setK("a");
    map.get(v.getK());
    

    PS: I have not tried to run this

提交回复
热议问题