重写equals和hashCode

时间:2024-05-14 00:06:08
equals()方法
1. 自反性:A.equals(A)要返回true.

2. 对称性:如果A.equals(B)返回true, 则B.equals(A)也要返回true.

3. 传递性:如果A.equals(B)为true, B.equals(C)为true, 则A.equals(C)也要为true. 说白了就是 A = B , B = C , 那么A = C.

4. 一致性:只要A,B对象的状态没有改变,A.equals(B)必须始终返回true.

5. A.equals(null) 要返回false.
//测试

public class Person {
private int age;
private String name;

  
@Override
public boolean equals(Object obj){
if(this == obj){
return true;
}else if(!(obj instanceof Person)){
return false;
}else{
Person p = (Person) obj;
return p.name.equals(name) && p.age == age;
}
} @Override
public int hashCode(){
int result = ;
result = result * + age;
result = result * + name.hashCode();
return result;
} public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
} }
//验证,如果不重写hashCode(),输出false;
   public static void main(String[] args) {
Person p = new Person();
p.setAge(3);
p.setName("ff");
Person p1 = new Person();
p1.setAge(3);
p1.setName("ff");
Set<Person> set = new HashSet<Person>();
set.add(p);
System.out.println(set.contains(p1));
}