Java: Check if enum contains a given string?

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

    This should do it:

    public static boolean contains(String test) {
    
        for (Choice c : Choice.values()) {
            if (c.name().equals(test)) {
                return true;
            }
        }
    
        return false;
    }
    

    This way means you do not have to worry about adding additional enum values later, they are all checked.

    Edit: If the enum is very large you could stick the values in a HashSet:

    public static HashSet getEnums() {
    
      HashSet values = new HashSet();
    
      for (Choice c : Choice.values()) {
          values.add(c.name());
      }
    
      return values;
    }
    

    Then you can just do: values.contains("your string") which returns true or false.

提交回复
热议问题