gpt4 book ai didi

java - 在包含被覆盖的 equals() 的类的子类中覆盖 equals()

转载 作者:行者123 更新时间:2023-11-30 06:32:05 31 4
gpt4 key购买 nike

我有一个 Point 类和一个 MinesweeperSquare 类,后者是前者的子类。如果我重写后者的 equals 方法,就像这样:

if (!(obj instanceof MinesweeperSquare)) {
return false;
}

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.

Point类中,我这样写:

if (!(obj instanceof Point)) {
return false;
}

如何在 MinesweeperSquare 中编写一个 equals 方法,使 equals 方法是对称的?

更新

如果我在 MinesweeperSquare 中编写以下内容,FindBugs 不会报告任何错误:

if (o == null || this.getClass() != o.getClass()) {
return false;
}

最佳答案

在您的新方法中,MinesweeperSquare.equals(Point) 将始终返回 false,但 Point.equals(MinesweeperSquare) 可能返回 true .在这种事情上使用 FindBugs 真是太好了。您可以在 PointMinesweeperSquare 的定义中使用 getClass() 来检查类是否完全相等......虽然这也很棘手。

关于java - 在包含被覆盖的 equals() 的类的子类中覆盖 equals(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9156543/

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