如何重写hashCode()和equals()方法
直接上刺刀了
定义一个学生类
class Student{
private String name;
private int age;
// getters and setters
}
重写equal方法
重写equal 使当学生的姓名和年龄相同时候就判断他们为同一个学生
1. 判断是否等于自身.
2使用instanceof运算符判断 other 是否为Student类型的对象.
3. 比较Student类中你自定义的数据域,name和age,一个都不能少.
具体代码如下
@Override
public boolean equals(Object other) {
System.out.println(“equals method invoked!”);
if(other == this)
return true;
if(!(other instanceof Student))
return false;
Studento = (Student)other;
return o.name.equals(name) && o.age == age;
}
重写equals()而不重写hashCode()的风险
构造一个hashset和两个对象
Set<Student> set = new HashSet<Student>();
set.add(c1);
Studentc1 = new Student(“yq1012”, 10);
Studentc2 = new Coder(“yq1012”, 10);
System.out.println(set.contains(c2)); //结果为false
因此,我们重写hashCode()的目的在于,在A.equals(B)返回true的情况下,A, B 的hashCode()要返回相同的值.
如何重写hashcode
@Override
public int hashCode() {
int result = 14;
result = result * 31 + name.hashCode();
result = result * 31 + age;
return result;
}
注:这里最好重写的时候不要返回固定值,如果hashCode()每次都返回相同的数,那么所有的对象都会被放到同一个bucket中,每次执行查找操作都会遍历链表,这样就完全失去了哈希的作用