Java enum valueOf() with multiple values?

前端 未结 6 822
庸人自扰
庸人自扰 2020-12-07 16:34

I have a problem in Java using Enums. I have read the documentation about assigning value parameters to Enums. But, my question is what about multiple values, is it possible

6条回答
  •  庸人自扰
    2020-12-07 17:19

    This is probably similar to what you're trying to achieve.

    public enum Language{
        English("english", "eng", "en", "en_GB", "en_US"),
        German("german", "de", "ge"),
        Croatian("croatian", "hr", "cro"),
        Russian("russian");
    
        private final List values;
    
        Language(String ...values) {
            this.values = Arrays.asList(values);
        }
    
        public List getValues() {
            return values;
        }
    }
    

    Remember enums are a class like the others; English("english", "eng", "en", "en_GB", "en_US") is calling the enum constructor.

    You could then retrieve the enum value corresponding to a string through a search method (you can put it as a static method in the enum again).

    public static Language find(String name) {
        for (Language lang : Language.values()) {
            if (lang.getValues().contains(name)) {
                return lang;
            }
        }
        return null;
    }
    

提交回复
热议问题