package test;
/**
* 判断两个对象的相等,首先判断hashcode,再equals
* 重写了equals,一般伴随着重写hashcode
*
* 重写equals一般要遵从如下的原则:
* 1、一致性 2、对称性 3、传递性 4、自反性 5、非空性
*
* 重写hashcode遵从的步骤:
* 1、如果该域是boolean类型,则计算(f?1:0)
* 2、如果是byte、char、short、int则转换成int类型
* 3、如果是long,则计算(int)(f^(f>>>32))
* 4、如果是float,则计算Float.floatToIntBits(f)
* 5、如果是double,则Double.doubleToLongBits(f),然后再按照步骤3
* 6、如果是对象,就用equals方法中递归的调用了对象的equals方法,则递归的调用hashcode
* 7、如果是数组,一般用Arrays.hashCode
* 最后调用公式:result = 31 * result + c
* @author zKF57533
*/
public class Student {
private String name;
private Integer age;
private String identityId;
public Student(){};
public Student(String name, String identityId) {
super();
this.name = name;
this.identityId = identityId;
}
public String getIdentityId() {
return identityId;
}
public void setIdentityId(String identityId) {
this.identityId = identityId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Student [age=" + age + ", name=" + name + "]";
}
@Override
public boolean equals(Object o){
//第一步判断是否是当前对象的引用
if(this == o){
return true;
}
//第二步判断是否是此类型
if(!(o instanceof Student)){
return false;
}
//第三步将o转换成此类型
Student s = (Student)o;
//第四部判断用来决定对象相等的关键字段
return this.name.equals(s.getName()) && this.identityId.equals(s.getIdentityId());
}
@Override
public int hashCode(){
int result = 19;//此值可以是任选的
result = 31 * result + name.hashCode();
result = 31 * result + identityId.hashCode();
return result;
}
public static void main(String[] args) {
Student s1 = new Student("name1","1234");
Student s2 = new Student("name1","1234");
System.out.println(s1.equals(s2)); //true
}
}