8 ADT和OOP中的“等价性”
Equivalence Relation
等价关系:自反、对称、传递
For a boolean-valued binary operation like == or equals(), the equivalence E is the set of pairs (x,y) for which the operation returns true.
Equality of Immutable Types
Using AF to define the quality, AF映射到同样的结果,则等价
- An equivalence relation induces an abstraction function (the relation partitions T, so f maps each element to its partition class).
- The relation induced by an abstraction function is an equivalence relation.
站在外部观察者角度:对两个对象调用任何相同的操作,都会得到相同的结果,则认为这两个对象是等价的。反之亦然!
== vs. equals()
The == operator compares references. It tests referential equality.
The equals() operation compares object contents – in other words, object equality.
在自定义ADT时,需要重写Object的equals()。
== 对基本数据类型,使用==判定相等
对对象类型,使用equals()
Implementing equals()
在Object中实现的缺省equals()是在判断引用等价性,这通常不是程序员所期望的。因此,需要重写。
注意区分Overload和override,重写时要使用 @Override ,编译器会检查超类中是否含有相同签名的函数。
In general, using instanceof in object-oriented programming is a bad smell. It should be disallowed anywhere except for implementing equals .
The Object contract
除非对象被修改了,否则调用多次equals应同样的结果
“相等”的对象,其 hashCode() 的结果必须 一致
Object ’s default hashCode() implementation is consistent with its default equals()
The standard is to compute a hash code for each component of the object that is used in the determination of equality (usually by calling the hashCode method of each component), and then combining these, throwing in a few arithmetic operations.
Always override hashCode() when you override equals()
Equality of Mutable Types
观察等价性:在不改变状态的情况下,两个mutable对象是否看起来一致
行为等价性:调用对象的任何方法都展示出一致的结果
对可变类型,实现行为等价性即可
也就是说,只有指向同样内存空间的objects,才是相等的。
所以对可变类型来说,无需重写这两个函数,直接继承Object的两个方法即可。
如果一定要判断两个可变对象看起来是否一致,最好定义一个新的方法。
Autoboxing and Equality