简体   繁体   中英

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?

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.

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;
   }   
// ...

You can use this too:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM