class Student{
private String name;
private int age;
}
equals:
@Override
public boolean equals(Object obj){
if(other == this) return true;
if(!(other instanceof Student)) return false;
Student o = (Student)other; return o.name.equals(name) && o.age == age;
}
hashcode 方法一:
@Override
public int hashCode() {
int result = 17;
result = result * 31 + name.hashCode();
result = result * 31 + age;
return result;
}
hashcode 方法二 jdk1.7:
@Override
public int hashCode() {
Objects.hash(name,age);
}
1.首先31是个质数,只能被1和本身整除的数,乘上后不容易出现重复
2.其次31这个数不大也不小,不至于超出返回类型的int,也不容易在乘上后重复
3.最后就是31=32-1=2^5 -1,计算方便,向左移动5位,再减一就行了