Java: Check if enum contains a given string?

后端 未结 29 1559
一个人的身影
一个人的身影 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 05:01

    You can make it as a contains method:

    enum choices {a1, a2, b1, b2};
    public boolean contains(String value){
        try{
            EnumSet.allOf(choices.class).contains(Enum.valueOf(choices.class, value));
            return true;
        }catch (Exception e) {
            return false;
        }
    }
    
    

    or you can just use it with your code block:

    try{
        EnumSet.allOf(choices.class).contains(Enum.valueOf(choices.class, "a1"));
        //do something
    }catch (Exception e) {
        //do something else
    }
    
    

提交回复
热议问题