Java: Check if enum contains a given string?

后端 未结 29 1498
一个人的身影
一个人的身影 2020-12-02 03:59

Here\'s my problem - I\'m looking for (if it even exists) the enum equivalent of ArrayList.contains();.

Here\'s a sample of my code problem:

<         


        
29条回答
  •  南方客
    南方客 (楼主)
    2020-12-02 04:40

    I don't think there is, but you can do something like this:

    enum choices {a1, a2, b1, b2};
    
    public static boolean exists(choices choice) {
       for(choice aChoice : choices.values()) {
          if(aChoice == choice) {
             return true;
          }
       }
       return false;
    }
    

    Edit:

    Please see Richard's version of this as it is more appropriate as this won't work unless you convert it to use Strings, which Richards does.

提交回复
热议问题