How to compare string with enum type in Java?

I have a list of listings of all states in the USA, as shown below:

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

and in my test file I read the input from a text file that contains the state. Since they are strings, how can I compare them with the value of an enumeration list in order to assign a value to a variable that I set as:

 private State state; 

I understand that I need to list a list of listings. However, since values ​​are not string types, how can you compare it? This is what I just type blindly. I don’t know if it is right or wrong.

 public void setState(String s) { for (State st : State.values()) { if (s == State.values().toString()) { s = State.valueOf(); break; } } } 
+8
java string enums compare
source share
3 answers

try it

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

You might want to handle an IllegalArgumentException that can be thrown if the value of "s" does not match "State"

+22
source share

Use the .name() method. Like st.name() . for example, State.AL.name() returns the string "AL".

So,

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

must work.

+4
source share

to compare enum with string

 for (Object s : State.values()) { if (theString.equals(s.toString())) { // theString is equal State object } } 
+2
source share

All Articles