Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comparing string with enumeration

Tags:

java

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.

like image 362
comatose Avatar asked May 11 '12 14:05

comatose


People also ask

Can I compare enum with string?

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 == .

Can you use == for enum?

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.

Why enums are better than strings?

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 .


3 Answers

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()))
like image 120
Tomasz Nurkiewicz Avatar answered Oct 09 '22 04:10

Tomasz Nurkiewicz


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.

like image 31
Juan Alberto López Cavallotti Avatar answered Oct 09 '22 03:10

Juan Alberto López Cavallotti


you can try

enum.SOMEVALUE.name()

as it

Returns the name of this enum constant, exactly as declared in its enum declaration.

like image 20
Alex Stybaev Avatar answered Oct 09 '22 03:10

Alex Stybaev