Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

equals method overrides equals in superclass and may not be symmetric

Tags:

java

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?

like image 635
Srinivasan Avatar asked Nov 30 '22 08:11

Srinivasan


2 Answers

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;
   }   
// ...
like image 35
Ilya Avatar answered Dec 02 '22 20:12

Ilya


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.

like image 155
SJuan76 Avatar answered Dec 02 '22 21:12

SJuan76