在实现equals方法之前我们应该明确,equals方法本身具备以下性质:
1.自反性:对于任何非空引用x,x.equals(x)应该返回true。
2.对称性:对于任何引用x和y,如果x.equals(y)返回true,那么y.equals(x)也应该返回true。
3.传递性:对于任何引用x、y和z,如果x.equals(y)返回true,y.equals(z)返回true,那么x.equals(z)也应该返回true。
4.一致性:如果x和y引用的对象没有发生变化,那么反复调用x.equals(y)应该返回同样的结果。
5.非空性:对于任意非空引用x,x.equals(null)应该返回false。
了解了以上性质之后我们便可以写出如下的equals方法:
class People{
private String name;
public People(String name){
this.name = name;
}
public String getName(){
return this.name;
}
public boolean equals(Object obj);
}
public boolean equals(Object obj){
if(this == obj)
return true;
if(obj == null)
return false;
if(this.getClass() != obj.getClass())
return false;
People tmp = (People)obj;
if(tmp.getName().equals(this.getName()))
return true;
return false;
}
609

被折叠的 条评论
为什么被折叠?



