Efficiently converting java string to its equivalent enum

前端 未结 3 1807
离开以前
离开以前 2021-01-26 02:26

Given a string i want to get the enum equivalent of it in constant time. I have a enum defined like the one shown in the question. Best way to create enum of strings?

         


        
3条回答
  •  一整个雨季
    2021-01-26 03:18

    I think you need to change the code to be :

    public enum Strings {
            STRING_ONE("ONE"), STRING_TWO("TWO");
    
            private String text;
    
            /**
             * @param text
             */
            private Strings(final String text) {
                this.text = text;
            }
    
            public String getText() {
                return this.text;
            }
    
            public static Strings getByTextValue(String text) {
                for (Strings str : Strings.values()) {
                    if (str.getText().equals(text)) {
                        return str;
                    }
                }
                return null;
            }
    
            /*
             * (non-Javadoc)
             * 
             * @see java.lang.Enum#toString()
             */
            @Override
            public String toString() {
                return text;
            }
        }
    

    Example :

    String test = "ONE";
    Strings testEnum = Strings.getByTextValue(test);
    

    now you have testEnum which is enum reference

提交回复
热议问题