抽象数据类型 (ADT)

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

请添加图片描述
请添加图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值