How to compare string to enum type in Java?

匿名 (未验证) 提交于 2019-12-03 08:41:19

问题:

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

回答1:

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"



回答2:

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

So,

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

should work.



回答3:

to compare enum to string

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


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!