gpt4 book ai didi

java - 是否存在 `==` 为真但 `equals` 为假的情况?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:08:26 27 4
gpt4 key购买 nike

在标准的Java API中,是否存在==会返回true,而equals会返回false<的场景?/。虽然从理论上讲,这可以像这样简单地写入用户定义的类中

class A {
public boolean equals(Object o) {
return this != o;
}
}

对于某些对象 bcb == c 是否会返回 true,但是 b.equals(c) 返回 false?此外,有这样的行为可能有什么好处吗?

最佳答案

没有*。

The contract for equals has 5 rules ,第一个涵盖了这种情况:

The equals method implements an equivalence relation on non-null object references:

  • It is reflexive: for any non-null reference value x, x.equals(x) should return true.
  • It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  • It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
  • It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
  • For any non-null reference value x, x.equals(null) should return false.

Java 标准库中任何违反自反性的对象都将是一个错误,如果您确实在 API 中发现了这样的对象,请将其报告给 Oracle。

*对于第三方库,可以说较少。开发人员犯了错误或者不了解 equals 契约。通常,这也属于第三方库中的错误,但 YMMV。

关于java - 是否存在 `==` 为真但 `equals` 为假的情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41749281/

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