这是我的问题-我正在寻找(如果它甚至存在)等价于ArrayList.contains();的enum。
下面是我的代码问题示例:
enum choices {a1, a2, b1, b2};
if(choices.???(a1)}{
//do this
}
现在,我意识到字符串的数组列表在这里是更好的路由,但我必须通过其他地方的开关/case运行我的enum内容。这就是我的问题所在。
假设这样的东西不存在,我该怎么做呢?
这是我的问题-我正在寻找(如果它甚至存在)等价于ArrayList.contains();的enum。
下面是我的代码问题示例:
enum choices {a1, a2, b1, b2};
if(choices.???(a1)}{
//do this
}
现在,我意识到字符串的数组列表在这里是更好的路由,但我必须通过其他地方的开关/case运行我的enum内容。这就是我的问题所在。
假设这样的东西不存在,我该怎么做呢?
当前回答
这种方法可以用来检查任何Enum,你可以把它添加到一个Utils类:
public static <T extends Enum<T>> boolean enumContains(Class<T> enumerator, String value)
{
for (T c : enumerator.getEnumConstants()) {
if (c.name().equals(value)) {
return true;
}
}
return false;
}
可以这样用:
boolean isContained = Utils.enumContains(choices.class, "value");
其他回答
你可以使用enumenumeof ()
enum Choices{A1, A2, B1, B2};
public class MainClass {
public static void main(String args[]) {
Choices day;
try {
day = Choices.valueOf("A1");
//yes
} catch (IllegalArgumentException ex) {
//nope
}
}
如果你希望检查经常失败,你可能会更好地使用一个简单的循环,就像其他人展示的那样——如果你的枚举包含很多值,可能会将一个HashSet或类似的枚举值转换为字符串并查询该HashSet。
这种方法可以用来检查任何Enum,你可以把它添加到一个Utils类:
public static <T extends Enum<T>> boolean enumContains(Class<T> enumerator, String value)
{
for (T c : enumerator.getEnumConstants()) {
if (c.name().equals(value)) {
return true;
}
}
return false;
}
可以这样用:
boolean isContained = Utils.enumContains(choices.class, "value");
枚举在Java中非常强大。你可以很容易地在枚举中添加contains方法(就像在类中添加方法一样):
enum choices {
a1, a2, b1, b2;
public boolean contains(String s)
{
if (s.equals("a1") || s.equals("a2") || s.equals("b1") || s.equals("b2"))
return true;
return false;
}
};
com.google.common.collect.Sets.newHashSet(MyEnum.values()).contains("myValue")
如果你想通过String查找,可以使用valueOf("a1")