Java:检查枚举是否包含给定的字符串? [英] Java: Check if enum contains a given string?
问题描述
这是我的问题...我正在寻找(如果它存在)枚举等价于ArrayList.contains();。
我的代码问题:
枚举选项{a1,a2,b1,b2};
if(choices。???(a1)} {
// do this
}
现在,我意识到Strings的ArrayList将是更好的路由,但是我必须通过其他地方的switch / case运行我的枚举内容,因此我的问题。
假设这样的事情不存在,我该怎么办?
谢谢!
应该这样做:
public static boolean contains(String test){
for(Choice c:Choice.values()){
if(c.name()。equals(test)){
返回true;
}
}
return false;
}
这样就意味着你不必担心稍后再添加枚举值,它们都被检查。
编辑: / b>如果枚举非常大,可以将值粘贴到HashSet中:
public static HashSet< String> g etEnums(){
HashSet< String> values = new HashSet< String>();
for(Choice c:Choice.values()){
values.add(c.name());
}
返回值;
}
然后你可以做: values.contains 你的字符串)
其返回true或false。
Here's my problem...I'm looking for (if it even exists) the enum equivalent of ArrayList.contains();.
Here's a sample of my code problem:
enum choices {a1, a2, b1, b2};
if(choices.???(a1)}{
//do this
}
Now, I realize that an ArrayList of Strings would be the better route here but I have to run my enum contents through a switch/case elsewhere. Hence my problem.
Assuming something like this doesn't exist, how could I go about doing it?
Thanks!
This should do it:
public static boolean contains(String test) {
for (Choice c : Choice.values()) {
if (c.name().equals(test)) {
return true;
}
}
return false;
}
This way means you do not have to worry about adding additional enum values later, they are all checked.
Edit: If the enum is very large you could stick the values in a HashSet:
public static HashSet<String> getEnums() {
HashSet<String> values = new HashSet<String>();
for (Choice c : Choice.values()) {
values.add(c.name());
}
return values;
}
Then you can just do: values.contains("your string")
which returns true or false.
这篇关于Java:检查枚举是否包含给定的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!