Efficiently converting java string to its equivalent enum

前端 未结 3 1805
离开以前
离开以前 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:03

    Since Enum.valueOf operates on the built-in name of the enum (i.e. "STRING_ONE" and "STRING_TWO") you would need to roll your own "registry" of name-to-enum, like this:

    public enum Strings {
        STRING_ONE("ONE"),
        STRING_TWO("TWO")
        ;
        private static final Map byName = new HashMap();
        private final String text;
    
        private Strings(final String text) {
            this.text = text;
        }
        static {
            for (Strings s : Strings.values()) {
                byName.put(s.toString(), s);
            }
        }
        @Override
        public String toString() {
            return text;
        }
        public static Strings forName(String name) {
            return byName.get(name);
        }
    }
    

    Demo.

    Above, a map from string name to enum Strings is used to do the translation. If the name is not there, null would be returned from the Strings.forName method.

提交回复
热议问题