等价方法的传递性 [英] Transitive nature of equals method

查看:186
本文介绍了等价方法的传递性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的合约等于(对象)方法指定要遵循的4个属性:自反,对称,传递和一致。虽然我理解不遵循Reflexive,Symmetric和Consistent的危险,并且绝对同意它的优点可以遵循传递,但我想知道如果它违反Transitive属性会带来什么伤害?

The contract for equals(object) method specifies 4 properties to follow: Reflexive, Symmetric, Transitive and Consistent. While I understand the danger of not following Reflexive, Symmetric and Consistent , and can definitely agree its good to follow transitive, I was wondering what harm it would bring if its violating the Transitive property?

具体来说,哪个Java库(或各种第三方库)需要依赖等于才能传递工作正常吗?根据我的理解,如果其他3个属性得到很好的实现,Collections框架将会起作用。

Specifically, which of the Java library (or various third party libraries) need the dependency upon equals to be transitive to work correctly? In my understanding, the Collections framework will work if the other 3 properties are well implemented.

推荐答案

假设有三个对象a,b, c with

Assume three objects a,b,c with

a == a, b == b, c == c (reflexive)
a == b, b == a
b == c, c == b
a != c, c != a

(伪代码, x == y 代表 x.equals(y))。

(Pseudocode, x == y stands for x.equals(y)).

现在,让我们将对象添加到集合中:

Now, let's add the objects to a set:

Set s = new HashSet(); // Set implementation doesn't matter
s.add(b); // s = [b]
s.add(a); // s doesn't change, because a == b
s.add(c); // s doesn't change, because c == b

相反,如果我们要添加它们的顺序不同:

In contrast, if we were to add them in a different order:

Set s = new HashSet();
s.add(a); // s = [a]
s.add(b); // s doesn't change, because b == a
s.add(c); // s = [a,c], because c != a

这显然是违反直觉的并且与预期的集合的行为不匹配。例如,它意味着两个集合的联合(即在 s.addAll(someOtherSet)之后的s的状态)可能取决于实现(元素的顺序) someOtherSet。

That is clearly counter-intuitive and doesn't match the behavior one would expect of a set. For example, it would mean that the union of two sets (i.e. the state of s after s.addAll(someOtherSet)) could depend on the implementation (order of elements) of someOtherSet.

这篇关于等价方法的传递性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆