This week's giveaway is in the EJB and other Java EE Technologies forum. We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line! See this thread for details.
Hi, I'm running FindBugs 2.3.3 through Maven 3.0.3. Also using Java 1.6. FindBugs is complaining about my equals method ...
with the error,
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.
The equals method of the super class is
I'm not sure what the error is complaining about. How can I rewrite my first "equals" method to make the error go away while achieving the same thing?
Imagine you have two nodes, one Node nand one TreeNodet. Both have an equal return value from toXML(). Now n.equals(t). However, since n is not a TreeNode, !t.equals(n). You just violated the Object.equals symmetry rule.
Usually, there are two solutions:
1) Don't override equals at all. Preferably, make it final in class Node. That does mean that two TextNodes will be equals if their XML values are equal but their text values are not.
2) Do not use instanceof but compare the classes:
In this case you can even shorten your TreeNode.equals method:
Now !n.equals(t) and !t.equals(n), since both have different classes.
Also, why are you using Boolean, Boolean.FALSE and Boolean.TRUE and not just boolean, false and true?