Monthly Archives: March 2012

Subtle equals bug in Java

The findbugs fairy discovered a little issue in my projects.

Bug: com.bfm.appl.blimp.marketdata.FXPricingSecurity overrides equals in PricingSecurity and may not be symmetric
Patternid: EQ_OVERRIDING_EQUALS_NOT_SYMMETRIC, type: Eq, category: CORRECTNESS

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.

Clear as mud? Let’s have a look at an example:

Continue reading

Tagged ,