File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes How do I write this equals method to satisfy findBugs (code checking tool)? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "How do I write this equals method to satisfy findBugs (code checking tool)?" Watch "How do I write this equals method to satisfy findBugs (code checking tool)?" New topic
Author

How do I write this equals method to satisfy findBugs (code checking tool)?

Dave Alvarado
Ranch Hand

Joined: Jul 02, 2008
Posts: 436
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?

Thanks, - Dave
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19718
    
  20

Imagine you have two nodes, one Node nand one TreeNode t. 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?


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Dave Alvarado
Ranch Hand

Joined: Jul 02, 2008
Posts: 436
Thanks, this is a great explanation.

I thought Boolean.TRUE had a performance advantage over just "true," but reading through the docs, it appears it doesn't, - Dave
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How do I write this equals method to satisfy findBugs (code checking tool)?