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

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

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

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

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

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


当前回答

一些假设: 1)没有尝试/捕捉,因为它是特殊的流量控制 2)“包含”方法必须是快速的,因为它通常运行几次。 3)空间不受限制(普通解决方案常见)

import java.util.HashSet;
import java.util.Set;

enum Choices {
    a1, a2, b1, b2;

    private static Set<String> _values = new HashSet<>();

    // O(n) - runs once
    static{
        for (Choices choice : Choices.values()) {
            _values.add(choice.name());
        }
    }

    // O(1) - runs several times
    public static boolean contains(String value){
        return _values.contains(value);
    }
}

其他回答

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

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);
}

枚举在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或以上版本,你可以这样做:

boolean isPresent(String testString){
      return Stream.of(Choices.values()).map(Enum::name).collect(Collectors.toSet()).contains(testString);
}

更好的是:

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;
  } 

};

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);
    ...