Enum : get the keys list
I'm looking forward to using the "google-api-translate-java" library.
In which there is a Language class. It's an enum allowing to provide the language name and to get it's value for Google Translate.I can easily get all the values with :
for (Language l : values()) {
// Here I loop on one value
}
But what I'd w开发者_开发技巧ant to get is a list of all the keys names (FRENCH, ENGLISH, ...).
Is there something like a "keys()" method that'd allow me to loop through all the enum's keys ?An alternative to Language.values()
is to use EnumSet
:
for (Language l : EnumSet.allOf(Language.class))
{
}
This is useful if you want to use it in an API which uses the collections interfaces instead of an array. (It also avoids creating the array to start with... but needs to perform other work instead, of course. It's all about trade-offs.)
In this particular case, values()
is probably more appropriate - but it's worth at least knowing about EnumSet
.
EDIT: Judging by another comment, you have a concern about toString()
being overridden - call name()
instead:
for (Language l : Language.values())
{
String name = l.name();
// Do stuff here
}
Try this:
for (Language l : Language.values()) {
l.name();
}
See also:
- http://www.java2s.com/Code/JavaAPI/java.lang/Enumvalues.htm
- http://java.sun.com/javase/6/docs/api/java/lang/Enum.html
- http://java.sun.com/docs/books/tutorial/java/javaOO/enum.html
Yes - If the enum is X, use X.values(). See in this tutorial.
精彩评论