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;
}
}
}
To compare a string with an enum, extend from the str class when declaring your enumeration class, e.g. class Color(str, Enum): . You will then be able to compare a string to an enum member using the equality operator == .
equals method uses == operator internally to check if two enum are equal. This means, You can compare Enum using both == and equals method.
The EnumUtils class has a method called isValidEnum whichChecks if the specified name is a valid enum for the class. It returns a boolean true if the String is contained in the Enum class, and a boolean false otherwise.
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"
Use .name()
method. Like st.name()
. e.g. State.AL.name()
returns string "AL".
So,
if(st.name().equalsIgnoreCase(s)) {
should work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With