Srinivasan
Srinivasan

Reputation: 12050

equals method overrides equals in superclass and may not be symmetric

I have below Findbugs error for my "equal" method,

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.

I can not post the code here for security violataion. Please let me know what is the error?

Upvotes: 4

Views: 14221

Answers (3)

Stéphane Tanguy
Stéphane Tanguy

Reputation: 33

You can use this too :

if (obj == null || !MyClass.class.isAssignableFrom(obj.getClass())) {
    return false;
}

Upvotes: 1

SJuan76
SJuan76

Reputation: 24895

It says that the contract of equals() implies that, a.equals(b) is true if and only if b.equals(a) is true.

If B extends A, in A.equals(Object obj) you probably will have

if !(obj instanceof A) return false;

and in B.equals(Object obj) you will have

if !(obj instanceof B) return false;

Here is the asymmetry: an instance of B makes (b instanceof A) true, while an instance of A makes (a instanceof B) false. So it means a risk than a.equals(b) is true and b.equals(a) is false.

Upvotes: 17

Ilya
Ilya

Reputation: 29693

You can use the similar construction to prevent this error:

public boolean equals(final Object obj)
{
   if (obj == null || getClass() != obj.getClass())
   {
      return false;
   } 
// ... 

instead of

public boolean equals(final Object obj)
{
   if (!(o instanceof UniversalIDDefinition))
   {
      return false;
   }   
// ...

Upvotes: 5

Related Questions