I am analyzing the following piece of code using a static analysis tool called FindBugs.
if(str.equals(enum.SOMEVALUE)) {// do something};
where str is a String and enum is an enumeration. The tool generates the following warning for this code, and states
This method calls equals(Object) on two references of different class types with no common subclasses. According to the contract of equals(), objects of different classes should always compare as unequal; therefore, according to the contract defined by java.lang.Object.equals(Object), the result of this comparison will always be false at runtime.
if I replace the above line of code with this:
if(str.equals(enum.SOMEVALUE.toString())) {// do something};
then the warning disappears.But I am not sure if the warning that the tool generates is really true and whether I am fixing it the right way ? because I’ve seen such comparisons before and it appears to be working correctly.
Your first comparison is basically wrong. You are comparing objects of completely different types (
StringandEnum) and they can never be equal. intellij even gives me a warning here. It compiles only becauseequals()acceptsObject, not aString.The second comparison is correct.
Although JavaDoc is a bit harsh on
name()method, I would actually advice using it in case given enum hastoString()overriden: