Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare string to enum type in Java?

I have an enum list of all the states in the US as following:

public enum State
{ AL, AK, AZ, AR, ..., WY }

and in my test file, I will read input from a text file that contain the state. Since they are string, how can I compare it to the value of enum list in order to assign value to the variable that I have set up as:

private State state;

I understand that I need to go through the enum list. However, since the values are not string type, how can you compare it? This is what I just type out blindly. I don't know if it's correct or not.

public void setState(String s)
{
    for (State st : State.values())
    {
        if (s == State.values().toString())
        {
           s = State.valueOf();
           break;
        }
    }
}
like image 511
Maximus Seng Avatar asked Oct 01 '12 23:10

Maximus Seng


People also ask

Can you compare string to enum?

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 == to compare enums in Java?

equals method uses == operator internally to check if two enum are equal. This means, You can compare Enum using both == and equals method.

How do I check if a string is enum?

The EnumUtils class has a method called isValidEnum whichChecks if the specified name is a valid enum for the class. It returns a boolean true if the String is contained in the Enum class, and a boolean false otherwise.


2 Answers

try this

public void setState(String s){
 state = State.valueOf(s);
}

You might want to handle the IllegalArgumentException that may be thrown if "s" value doesn't match any "State"

like image 28
maestr0 Avatar answered Sep 29 '22 22:09

maestr0


Use .name() method. Like st.name(). e.g. State.AL.name() returns string "AL".

So,

if(st.name().equalsIgnoreCase(s)) {

should work.

like image 134
Bhesh Gurung Avatar answered Sep 29 '22 22:09

Bhesh Gurung