I have two different enums and i want to be able to output whether a given string is a part of a enum collection. this is my code:
public class Check {
public enum Filter{SIZE, DATE, NAME};
public enum Action{COPY, DELETE, REMOVE};
public boolean isInEnum(String value, Enum e){
// check if string value is a part of a given enum
return false;
}
public void main(){
String filter = "SIZE";
String action = "DELETE";
// check the strings
isInEnum(filter, Filter);
isInEnum(action, Action);
}
}
eclipse says that in the last two lines "Filter can't be resolved to a variable" but apart from that it seems that the Enum param in the function "isInEnum" is wrong.
Something is very wrong here can anyone help?
Comparing String to Enum type in JavaFor comparing String to Enum type you should convert enum to string and then compare them. For that you can use toString() method or name() method. toString()- Returns the name of this enum constant, as contained in the declaration.
Enum. IsDefined is a check used to determine whether the values exist in the enumeration before they are used in your code. This method returns a bool value, where a true indicates that the enumeration value is defined in this enumeration and false indicates that it is not. The Enum .
To lookup a Java enum from its string value, we can use the built-in valueOf method of the Enum. However, if the provided value is null, the method will throw a NullPointerException exception. And if the provided value is not existed, an IllegalArgumentException exception.
The simplest (and usually most efficient) way is as follows:
public <E extends Enum<E>> boolean isInEnum(String value, Class<E> enumClass) {
for (E e : enumClass.getEnumConstants()) {
if(e.name().equals(value)) { return true; }
}
return false;
}
and then you call isInEnum(filter, Filter.class)
.
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