How to compare string to enum type in Java?

后端 未结 3 629
无人共我
无人共我 2021-01-11 18:36

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 rea

相关标签:
3条回答
  • 2021-01-11 19:08

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

    So,

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

    should work.

    0 讨论(0)
  • 2021-01-11 19:26

    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"

    0 讨论(0)
  • 2021-01-11 19:27

    to compare enum to string

    for (Object s : State.values())
        {
                if (theString.equals(s.toString()))
            {
                // theString is equal State object
    
            }
        }
    
    0 讨论(0)
提交回复
热议问题