File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Dave Alvarado
Ranch Hand
Posts: 436
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20398
47
Chrome Eclipse IDE Java Windows
  • 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Dave Alvarado
Ranch Hand
Posts: 436
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic