这是我的问题-我正在寻找(如果它甚至存在)等价于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内容。这就是我的问题所在。
假设这样的东西不存在,我该怎么做呢?
当前回答
您可以先将枚举转换为List,然后使用List contains方法
enum Choices{A1, A2, B1, B2};
List choices = Arrays.asList(Choices.values());
//compare with enum value
if(choices.contains(Choices.A1)){
//do something
}
//compare with String value
if(choices.contains(Choices.valueOf("A1"))){
//do something
}
其他回答
这种方法可以用来检查任何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");
这应该做到:
public static boolean contains(String test) {
for (Choice c : Choice.values()) {
if (c.name().equals(test)) {
return true;
}
}
return false;
}
这种方式意味着你不必担心以后添加额外的enum值,它们都是被检查的。
编辑:如果枚举非常大,你可以把值放在HashSet中:
public static HashSet<String> getEnums() {
HashSet<String> values = new HashSet<String>();
for (Choice c : Choice.values()) {
values.add(c.name());
}
return values;
}
然后你就可以做:价值观。包含("your string"),返回true或false。
EnumUtils。如果你想导入Apache commons lang3, isValidEnum可能是最好的选择。如果不是下面是一个通用函数,我会用作替代。
private <T extends Enum<T>> boolean enumValueExists(Class<T> enumType, String value) {
boolean result;
try {
Enum.valueOf(enumType, value);
result = true;
} catch (IllegalArgumentException e) {
result = false;
}
return result;
}
然后像下面这样使用
if (enumValueExists(MyEnum.class, configValue)) {
// happy code
} else {
// angry code
}
我会写,
Arrays.stream(Choice.values()).map(Enum::name).collect(Collectors.toList()).contains("a1");
Enum#equals只适用于对象比较。
番石榴可以成为你的朋友
比如这个:
enum MyData {
ONE,
TWO
}
@Test
public void test() {
if (!Enums.getIfPresent(MyData.class, "THREE").isPresent()) {
System.out.println("THREE is not here");
}
}