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 getEnums() {
HashSet values = new HashSet();
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中寻找类似ArrayList.contains()方法的枚举实现。作者提出了一个解决方案,即通过遍历枚举值并比较名称来检查枚举是否包含特定值。如果枚举非常大,建议使用HashSet以提高查找效率。
2010

被折叠的 条评论
为什么被折叠?



