这是我的问题-我正在寻找(如果它甚至存在)等价于ArrayList.contains();的enum。

下面是我的代码问题示例:

enum choices {a1, a2, b1, b2};

if(choices.???(a1)}{
//do this
} 

现在,我意识到字符串的数组列表在这里是更好的路由,但我必须通过其他地方的开关/case运行我的enum内容。这就是我的问题所在。

假设这样的东西不存在,我该怎么做呢?


当前回答

枚举在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;
  } 

};

其他回答

Java 8+流+设置方式:

    // Build the set.
    final Set<String> mySet = Arrays//
      .stream(YourEnumHere.values())//
      .map(Enum::name)//
      .collect(Collectors.toSet());

    // Reuse the set for contains multiple times.
    mySet.contains(textA);
    mySet.contains(textB);
    ...

它是一个枚举,这些都是常量值,所以如果它在switch语句中,它就像这样做:

case: val1
case: val2

还有,为什么你需要知道什么被声明为常数?

虽然迭代一个列表或捕捉一个异常对于大多数情况来说已经足够好了,但我正在寻找一些可重用的东西,这些东西对于大型枚举来说也很好。最后,我写下了这样一段话:

public class EnumValidator {

    private final Set<String> values;

    private EnumValidator(Set<String> values) {
        this.values = values;
    }

    public static <T extends Enum<T>> EnumValidator of(Class<T> enumType){
        return new EnumValidator(Stream.of(enumType.getEnumConstants()).map(Enum::name).collect(Collectors.toSet()));
    }

    public boolean isPresent(String et){
        return values.contains(et);
    }
    
}

这个对我很有用:

Arrays.asList(YourEnum.values()).toString().contains("valueToCheck");

我为这个验证创建了下一个类

public class EnumUtils {

    public static boolean isPresent(Enum enumArray[], String name) {
        for (Enum element: enumArray ) {
            if(element.toString().equals(name))
                return true;
        }
        return false;
    }

}

用法示例:

public ArrivalEnum findArrivalEnum(String name) {

    if (!EnumUtils.isPresent(ArrivalEnum.values(), name))
        throw new EnumConstantNotPresentException(ArrivalEnum.class,"Arrival value must be 'FROM_AIRPORT' or 'TO_AIRPORT' ");

    return ArrivalEnum.valueOf(name);
}