如果HashMap的key为一个学生,value值为一个学生的成绩,我们希望通过学生对象查询到学生的成绩
public class Main {
public static void main(String[] args){
Student student1=new Student("1","tom",20);
Student student2=new Student("1","tom",20);
Map<Student,Integer> map=new HashMap<>();
map.put(student1,100);
System.out.println(student1.hashCode()+"::"+student2);
System.out.println(map.get(student1)+"::"+map.get(student2));
}
}
class Student {
private String type;
private String name;
private int age;
Student(String type,String name,int age){
this.age=age;
this.type=type;
this.name=name;
}
}
输出:
com.example.demo.Student@deb6432::com.example.demo.Student@28ba21f3
100::null
虽然我们的student1和student2是都是tom但是却无法成功通过student2获取到student1,因为创建了两次对象,对象地址不一致,而HashMap就是通过对象的=hashCode()和equals判定是否为同一个key,这就需要我们重写这两个方法
这里提供一种金典的hash算法
public class Main {
public static void main(String[] args){
Student student1=new Student("1","tom",20);
Student student2=new Student("1","tom",20);
Map<Student,Integer> map=new HashMap<>();
map.put(student1,100);
System.out.println(student1+"::"+student2);
System.out.println(map.get(student1)+"::"+map.get(student2));
}
}
class Student {
private String type;
private String name;
private int age;
Student(String type,String name,int age){
this.age=age;
this.type=type;
this.name=name;
}
@Override
public int hashCode() {
int B=31; // 31 131 1313 13131 131313 etc..
int hash=0;
hash=hash*B+age;
hash=hash*B+type.toUpperCase().hashCode();
hash=hash*B+name.toUpperCase().hashCode();
return hash;
}
@Override
public boolean equals(Object obj) {
if(this==obj){
return true;
}
if(obj==null){
return false;
}
Student student=(Student) obj;
return student.type.toUpperCase().equals(this.type.toUpperCase())&&
student.age==this.age&&student.name.toUpperCase().equals(this.name.toUpperCase());
}
}
输出:
com.example.demo.Student@19635::com.example.demo.Student@19635
100::100
如果对hashCode有更高的要求,可以使用MD5,sha之类的算法