判断ADT中的等价性
前言:在很多场景下,需要判定两个对象是否“相等”,本文主要讨论==和equals的区别。
一.引用等价性 ==
对基本数据类型,使用==判定相等
二.对象等价性 equals
1.对对象类型,使用equals判定相等
2.equals的实现:
public class Object{
...
public boolean equals(Object that){
return this == that; //在对象等价性的判断是用引用等价性实现的
}
}
一般来说,这个equals的实现通常不是程序员所期待的,所以一般需要重写
3.错误示例:
public class Duration{
...
public boolean equals(Duration that){
return this.getLength() == that.getLength()
}
}
Duration d1 = new Duration(1, 2);
Duration d2 = new Duration(1, 2);
Object o2 = d2;
d1.equals(d2); //结果为true
d1.equals(o2); //结果为false
d2是Duration类型,所以传入参数时实现的是Duration中的equals,即判断长度相等,所以结果为true;而o2是Object类型,所以传入参数时实现的是Object中的equals,即通过引用等价性进行判断,由于d1和o2是两个不同的对象,所以结果为false.
!!原因是上面equals的实现并不是重写,而是重载,因为改变了参数的类型。
4.重写equals的方法
@Override
public boolwan equals(Object that){
return that instanceof Duration && this.sameValue((Duration)that);
}
private boolean sameValue(Duration that){
return this.getLength == that.getLength();
}
5.对于可变类型的等价性
实现行为等价性即可,而且无需重写equals和hashcode两个函数