问题
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
}
}
来源:https://stackoverflow.com/questions/12682553/how-to-compare-string-to-enum-type-in-java