I have a Point class and a MinesweeperSquare class, the latter being a subclass of the former. If I override the equals method in the latter, like so:
if (!(obj instanceof MinesweeperSquare)) {
return false;
}
FindBugs reports that:
This class defines an equals method that overrides an equals method in a superclass. Both equals methods
methods useinstanceofin 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.
In the Point class, I wrote:
if (!(obj instanceof Point)) {
return false;
}
How do I write an equals method in MinesweeperSquare such that the equals method is symmetric?
Update
FindBugs reports no errors if I write the following in MinesweeperSquare:
if (o == null || this.getClass() != o.getClass()) {
return false;
}
In your new method,
MinesweeperSquare.equals(Point)will always return false, butPoint.equals(MinesweeperSquare)could returntrue. Good on you for using FindBugs on this sort of thing. You might be able to usegetClass()in both the definition ofPointandMinesweeperSquareto check if the classes are exactly equal…although this, too, is tricky.