1. 什么是equals和hashcode
equals 是判断两个对象是否相等,如果不重写的话就是使用的object类中的equals方法,使用的是==作为判断依据,重写了的话就是根据你自定义的形式判断对象是否相等。
hashcode是object中的本地方法,返回的是对象的散列值,同一个对象的散列值相等的。 equals和hashcode我觉得这两者并没有必然的关系,有联系的点在于都可以判断对象是否相等。接下来我们来看三种情况,分别为equals和hashcode都不重写;重写equals;重写equals和hashcode三种情况。
- 当都不重写hashcode和equals时候
public class student2 {
private String name;
private int id;
public student2(int id,String name){
this.name = name;
this.id = id;
}
}
student2 student = new student2(1,"cp");
student2 student1 = new student2(2,"hh");
System.out.println(student.hashCode()==student1.hashCode());//false
System.out.println(student.equals(student1));//false
- 当重写equals时,不重写hashcode时,存储在equals判断为相等的对象,但是在hashmap中确会重复存储。
public class student2 {
private String name;
private int id;
public student2(int id,String name){
this.name = name;
this.id = id;
}
@Override
public boolean equals(Object obj) {
student2 temp = (student2)obj;
if(temp.name==this.name) return true;
else return false;
}
}
student2 student = new student2(1,"cp");
student2 student1 = new student2(2,"cp");
System.out.println(student.hashCode()==student1.hashCode());//false
System.out.println(student.equals(student1));//true
HashMap<student2,Integer> hashMap = new HashMap();
hashMap.put(student,1);
hashMap.put(student1,2);
for (student2 s:
hashMap.keySet()) {
System.out.println(s.getId());
}
//输出 1 , 2
- 重写equals,和hashcode时。hashmap在存储时就不会存储相同的元素。
public class student2 {
private String name;
private int id;
public student2(int id,String name){
this.name = name;
this.id = id;
}
@Override
public boolean equals(Object obj) {
student2 temp = (student2)obj;
if(temp.name==this.name) return true;
else return false;
}
@Override
public int hashCode() {
return this.name.hashCode();
}
student2 student = new student2(1,"cp");
student2 student1 = new student2(2,"cp");
System.out.println(student.hashCode()==student1.hashCode());//true
System.out.println(student.equals(student1));//true
HashMap<student2,Integer> hashMap = new HashMap();
hashMap.put(student,1);
hashMap.put(student1,2);
for (student2 s:
hashMap.keySet()) {
System.out.println(s.getId());
}
// 1
总结
hashcode和equals本没有必然的联系,而是如果需要存储在hashmap,hashtable,hashset等数据结构中时就需要重写,因为这种数据结构在存储值时会计算hashcode计算下标值,再通过equals判断值时候相等。