gpt4 book ai didi

java - 覆盖 equals 和 hashCode 只是为了调用 super.equals/hashCode 还是抛出 AssertionError?

转载 作者:行者123 更新时间:2023-11-30 06:37:36 26 4
gpt4 key购买 nike

是否有最佳实践,何时覆盖 equals?

我应该覆盖 equals/hashCode 并抛出 AssertionError 吗?只是为了确保没有人使用它? (如 Effective Java 一书中所推荐的)

我是否应该覆盖 equals/hashCode 并只调用 super.equals/hashCode,因为父类(super class)的行为是相同的? (FindBugs推荐这个,因为我加了一个字段)

它们真的是最佳实践吗?

最佳答案

错误

您不应该从 equalshashCode 方法中抛出异常。 equals 和 hashCode 方法随处可见,在这里乱抛异常可能会害了你。

断言错误

你不应该直接抛出 AssertionError。将 assert 语句放入任何方法都可以,因为当断言关闭时这些语句将不会运行。

何时覆盖

如果父类(super class)方法是 Object.equals,则覆盖并直接传递给 super.equals() 没有坏处。

如果您比较的两个对象是不同类型的,那么您可能会陷入破坏对称性的陷阱,即 x.equals(y) 为真但 y.equals( x) 为假。如果 y 是 x 的子类,则可能会发生这种情况,因此 y 的 equals 方法可能会进行稍微不同的比较。您可以使用 if (getClass() != obj.getClass()) return false; 在 equals 方法中检查这一点。

最佳实践

Effective Java是一个很好的资源,特别是关于如何最好地实现 hashCode() 方法。请务必阅读并考虑 equals 的契约(Contract)和 hashCode列在 Javadoc 中,并确保如果您重写一个,则重写另一个。 eclipse 中的“Generate hashCode() and equals”函数可以很好地提供您在这些方法中所需的内容,因此请检查它为您的类生成的代码。以下摘自Javadoc of java.lang.Object .

equals Contract:

  • 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.

hashCode Contract:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

关于java - 覆盖 equals 和 hashCode 只是为了调用 super.equals/hashCode 还是抛出 AssertionError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3223061/

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