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.
To compare a string with an enum, extend from the str class when declaring your enumeration class, e.g. class Color(str, Enum): . You will then be able to compare a string to an enum member using the equality operator == .
Because there is only one instance of each enum constant, it is permissible to use the == operator in place of the equals method when comparing two object references if it is known that at least one of them refers to an enum constant.
I would consider Enums to be a better approach than Strings. They are type safe and comparing them is faster than comparing Strings. Show activity on this post. If your set of parameters is limited and known at compile time, use enum .
Your first comparison is basically wrong. You are comparing objects of completely different types (String
and Enum
) and they can never be equal. intellij even gives me a warning here. It compiles only because equals()
accepts Object
, not a String
.
The second comparison is correct.
Although JavaDoc is a bit harsh on name()
method, I would actually advice using it in case given enum has toString()
overriden:
if(str.equals(FooEnum.SOMEVALUE.name()))
I think replacing the constant for the toString()
may be the right thing to do, I would change it for .name()
though because toString is to be overriden.
you can try
enum.SOMEVALUE.name()
as it
Returns the name of this enum constant, exactly as declared in its enum declaration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With