Java: Check if enum contains a given string?

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

    Few assumptions:
    1) No try/catch, as it is exceptional flow control
    2) 'contains' method has to be quick, as it usually runs several times.
    3) Space is not limited (common for ordinary solutions)

    import java.util.HashSet;
    import java.util.Set;
    
    enum Choices {
        a1, a2, b1, b2;
    
        private static Set _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);
        }
    }
    

提交回复
热议问题