Junior — Senior
The impact of changing key object fields on HashMap operation
livecode
Task condition
In the example, an object of the class Key is created, which acts as a key for the HashMap. After the object is placed into the map, its id field is changed, and then the same object is used to insert a new value. What will be the final state of the map: one key with a new value or two separate keys? Explain how HashMap handles such changes.
import java.util.HashMap;
import java.util.Map;
public class JetbulbInterview {
public static void main(String[] args) {
Map<Key, String> map = new HashMap<>();
Key key = new Key(1, "1");
map.put(key, "One");
key.id = 22;
map.put(key, "Two");
System.out.println(map);
}
}
class Key {
int id;
String name;
public Key(int id, String name) {
this.id = id;
this.name = name;
}
}