gpt4 book ai didi

java - equals 方法覆盖父类(super class)中的 equals 并且可能不对称

转载 作者:行者123 更新时间:2023-12-04 21:54:15 25 4
gpt4 key购买 nike

我的“相等”方法有以下 Findbugs 错误,

This class defines an equals method that overrides an equals method in a superclass. Both equals methods methods use instanceof in the determination of whether two objects are equal. This is fraught with peril, since it is important that the equals method is symmetrical (in other words, a.equals(b) == b.equals(a)). If B is a subtype of A, and A's equals method checks that the argument is an instanceof A, and B's equals method checks that the argument is an instanceof B, it is quite likely that the equivalence relation defined by these methods is not symmetric.



我不能在这里发布安全违规代码。请让我知道错误是什么?

最佳答案

上面写着equals()的契约(Contract)意味着,a.equals(b)为真当且仅当 b.equals(a)是真的。

如果 B 扩展 A,则在 A.equals(Object obj)你可能会有

if !(obj instanceof A) return false;

并在 B.equals(Object obj)你将会有
if !(obj instanceof B) return false;

这是不对称性:B 的实例使 ( b instanceof A ) 为真,而 A 的实例使 ( a instanceof B ) 为假。所以这意味着风险比 a.equals(b)是真的和 b.equals(a)是假的。

关于java - equals 方法覆盖父类(super class)中的 equals 并且可能不对称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6518534/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com