public class Person{
private String name;
private int age;
}
setter和getter方法已省略
测试类中:
HashSet<Person> hs = new HashSet<>();
hs.add(new Person("a",1));
hs.add(new Person("a",1));
hs.add(new Person("b",2));
hs.add(new Person("c",3));
如果姓名和年龄字段相同就表明为同一个对象
重写了hashCode()方法就可以执行Person中重写的equals()方法。
Person类中重写两个方法(ME自动自成 )
@Override
public int hashCode() {
/**
* final int prime = 31;
* 1,31是一个质数
* 2,31不大不小
* 3,2^5 - 1 = 31
*/
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}