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

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

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

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

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

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


当前回答

你可以用这个

YourEnum {A1, A2, B1, B2}

boolean contains(String str){ 
    return Sets.newHashSet(YourEnum.values()).contains(str);
}                                  

@wightwulf1944建议的更新被纳入,使解决方案更有效。

其他回答

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

};
  Set.of(CustomType.values())
     .contains(customTypevalue) 

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

case: val1
case: val2

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

如果你想通过String查找,可以使用valueOf("a1")

为什么不将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;
        }
}