/**
为保证向Set中添加的对象其所在的类必须要重写hashCode和equals方法:
重写的原则:hashCode和equals尽量保持一致性:
两个相同的对象equals()返回true时,那么两个对象的hashCode()必须返回相同的哈希值
同一对象多次调用hashCode()应返回相同的哈希值
对象中用作equals()的域,一般也要在hashCode()中用到。
*/
public class HashCodeAndEquals {
public static void main(String[] args) {
}
}
public class Person {
int age;
String name;
public Person() {
}
public Person(int age, String name) {
this.age = age;
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
if (age != person.age) return false;
return name != null ? name.equals(person.name) : person.name == null;
}
@Override
//IDEA重写hashCode()方法,用31原因:
//31是较大的素数,减少冲突
//31只有5bits,防止溢出
//i*31=i<<5-1 许多虚拟机里都有优化,提高效率
public int hashCode() {
int result = age;
result = 31 * result + (name != null ? name.hashCode() : 0);
return result;
}
}
原文:https://www.cnblogs.com/WhiteThornZzf/p/14490876.html