How to compare string to enum type in Java?

compare, enums, java, string

Solution

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"

Problem

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; } } } ```

Original source