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?
This what I would like to achieve:
I have an Enum for languages. Each language is represented by its name and some shorter aliases (not always, and not always the same number of aliases)
Here is an example:
public enum Language{
English("english", "eng", "en", "en_GB", "en_US"),
German("german", "de", "ge"),
Croatian("croatian", "hr", "cro"),
Russian("russian")
}
Can I just define an Enum like this and get the right enum values by calling Language.valueOf() ???
解决方案
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;
}