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");
HashMap<K,V> map = new HashMap<K,V>();
map.put(v.getk(),v);
v.setK("b");
As far as I know, this should cause some kind of problem because a map key is supposed to be invariable. What would happen here?
Edit: Consider the key not to be a String but a mutable object as stated in the coment below.
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}
and now you do
then you would face the problem — you mutated the object used as the map key.