Strange Findbugs error with equals
I have equals this method, but Findbugs is reporting error, any idea?
@Overr开发者_StackOverflow社区ide
public boolean equals(final Object obj) {
return obj instanceof String && this.value != null
&& this.value.equals(obj); // this.value is a String
}
The error is :
Myclass.equals(Object)
checks for operand being a String
Your implementation of equals for your MyClass
will break at least the symmetric- and reflexive properties of the equals-contract:
symmetric:
for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
In your case:
MyClass A
for example with value="a":
A.equals("a")
will be true, but "a".equals(A)
is false. This violates the symmetric-property.
reflexive:
for any non-null reference value x, x.equals(x) should return true.
But your implementation will return false for
A.equals(A)
but must return true.
Etc.
Your equals implementation sure is strange.
For one it looks very much like its violating the requirements of
a.equals(a) == true
=== Update in response to the comment ===
This is part of the contract of equals: http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html#equals%28java.lang.Object%29
This kind of behavior is important when you put your Object into a Set or Map. Without the mentioned property you would get the weired behavior that you can add an instance to a Set and afterwards calling contains on the set with the exact same object as an argument would result in false.
=== Another update in response to your changed question ===
Since you check that the operand is a String, but your class isn't a subclass of String, an instance of your class will never be equal to itself according to your definition of equals. Also as stated by another answer symmetry will be broken.
This might be helpful as well: http://findbugs.sourceforge.net/bugDescriptions.html#EQ_CHECK_FOR_OPERAND_NOT_COMPATIBLE_WITH_THIS
@Override
public boolean equals(final Object obj) {
return (obj instanceof YourClass) && (this.value.equals(((YourClass)obj).value)); // this.value is a String
}
As I understand Findbugs points to potential bugs.
精彩评论