In Java: what happens if I change a key in a HashMap to equal another key?
See English answers > changing an object which is used as a map key
But what if I change the existing key to be equal to another existing key?
In this case, map How will the get () method behave (apply to one of the equal keys)?
The following is a very simple example
public class Person{ private int age; private String name; public Person(int a,String n){ age = a; name = n; } public void setAge(int a){ age = a; } public int getAge(){return age; } public String getName() {return name; } @Override public boolean equals(Object o){ if(!(o instanceof Person)){return false;} Person p = (Person) o; return ((p.getName().equals(this.getName())) && (p.getAge() == this.getAge())); } @Override public int hashCode(){return age;} } public class MainClass{ public static void main(String[]args){ Person p1 = new Person("Bill",20); Person p2 = new Person("Bill",21); HashMap<Person,String> map = new HashMap<>(); map.put(p1,"some value"); map.put(p2,"another value"); p1.setAge(21); String x = map.get(p1); // <-- What will this be?? System.out.println(x); } }
Solution
When you change the existing key in the HashMap, you will destroy the HashMap You should not change the keys that exist in the HashMap If you have to change these keys, you should remove them from the HashMap before you change them and put them into the HashMap again after you change them
map. Get (P1) will search for the key P1 according to its new hashcode, which is equal to the hash code of P2 Therefore, it will search in the bucket containing P2 and return the corresponding value – "another value" (unless two keys are mapped to the same bucket, in which case either value can be returned, depending on whether the key to be tested is equal first)