开发者

equals method overrides equals in superclass and may not be symmetric

开发者 https://www.devze.com 2023-03-15 23:15 出处:网络
I have below Findbugs error for my \"equal\" method, This class defines an equals method that overrides an equals method in a

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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消