https://blog.csdn.net/lettyisme/article/details/80339637 我自己之前的总结
首先要知道equals方法得特性:自反性,,,,,,
自反性:对于任何非null的引用值x,x.equals(x)=true
对称性:对于任何非null的引用x,y,x.equals(y)=true,同样y.equals(y)=true
传递性:对于任何非null的引用x,y,z,x.equals(y)=true,x.equals(z)=true =>y.equals(z)=true
一致性:对于任何非null的引用x和y,只要equals的操作涉及的类信息没有改变,则x.equals(y)的结果一直不变;
对于任何为null的引用,null.equals(x)=false
重写equals方法的四个步骤:
(1)使用==操作符判断参数是否是这个对象的引用;//这个什么意思?
(2)使用instanceof操作符判断”参数是否是正确的类型“;
(3)把参数装换成正确的类型;
(4)对于参数中的各个域,判断其是否和对象中的域相匹配;
public boolean equals(Object obj) {//传入的参数是要比较的那个类吧
if(this==obj){
return true;
}
if(!(obj instanceof User)){
return false;
}
final User user = (User) obj;
if( this.userId == user.userId &&
this.userName.equals(user.userName) &&
this.password.equals(user.password) &&
this.gender == user.gender
){
return true;
}
return false;
}
public int hashCode(){
int result = 0;
result = this.userName.hashCode() + this.password.hashCode();
result = this.gender.hashCode() + result;
return result;
}
可能会拓展考一下怎么计算hashcod