Java: Check if enum contains a given string?

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

    This combines all of the approaches from previous methods and should have equivalent performance. It can be used for any enum, inlines the "Edit" solution from @Richard H, and uses Exceptions for invalid values like @bestsss. The only tradeoff is that the class needs to be specified, but that turns this into a two-liner.

    import java.util.EnumSet;
    
    public class HelloWorld {
    
    static enum Choices {a1, a2, b1, b2}
    
    public static > boolean contains(Class _enumClass, String value) {
        try {
            return EnumSet.allOf(_enumClass).contains(Enum.valueOf(_enumClass, value));    
        } catch (Exception e) {
            return false; 
        }
    }
    
    public static void main(String[] args) {
        for (String value : new String[] {"a1", "a3", null}) {
            System.out.println(contains(Choices.class, value));
        }
    }
    

    }

提交回复
热议问题