HashMap is a very dangerous thing to use mutable objects as keys
Let's start with a simple example
class People{
private String name;
private int age;
public People(){
}
public People(String name, int age) {
this.name = name;
this.age = age;
}
}
public class Main {
public static void main(String[] args) {
Map<People,Integer> map = new HashMap<People, Integer>();
map.put(new People("liu",18),5);
map.put(new People("cheng",22),1);
People p = new People("liu",18);
People p1 = new People("cheng",22);
System.out.println(map.get(p));
System.out.println(map.get(p1));
}
}
In the above example, the execution result is:
Why is this?
This is because the equals method and the hashCode method are executed when the element is get.
When a new object is new, the address changes, and there is no guarantee that the hash value and the equals result are still the same. Therefore, the corresponding value cannot be obtained.
How to solve it?
The hashCode method and the equals method are called by default when fetching and inserting, so we can rewrite these two methods.
as follows :
class People{
private String name;
private int age;
public People(){
}
public People(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object obj) {
if (this == obj)return true;
if(obj == null||getClass()!=obj.getClass()){
return false;
}
People p = (People)obj;
if(name!=null?!name.equals(p.name):p.name!=null){
return false;
}
if (age!=0?age!=(p.age):p.age!=0){
return false;
}
return true;
}
@Override
public int hashCode() {
return name!=null&&age!=0?name.hashCode()+
((Integer)age).hashCode():0;
}
}
The rewrite of the hashCode method is a bit low!
After rewriting, we run the result like this:
After rewriting, it is found that the value can be obtained, but is it difficult to find that the method is rewritten in this process? ?
This is only for objects with only two member variables, if there are many member variables! That would seem troublesome