这是我的问题-我正在寻找(如果它甚至存在)等价于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内容。这就是我的问题所在。
假设这样的东西不存在,我该怎么做呢?
当前回答
请使用Apache commons lang3库
EnumUtils.isValidEnum(MyEnum.class, myValue)
其他回答
更好的是:
enum choices {
a1, a2, b1, b2;
public static boolean contains(String s)
{
for(choices choice:values())
if (choice.name().equals(s))
return true;
return false;
}
};
为什么不将Pablo的回复与valueOf()结合起来呢?
public enum Choices
{
a1, a2, b1, b2;
public static boolean contains(String s) {
try {
Choices.valueOf(s);
return true;
} catch (Exception e) {
return false;
}
}
我会写,
Arrays.stream(Choice.values()).map(Enum::name).collect(Collectors.toList()).contains("a1");
Enum#equals只适用于对象比较。
如果你想通过String查找,可以使用valueOf("a1")
com.google.common.collect.Sets.newHashSet(MyEnum.values()).contains("myValue")