tags:

views:

136

answers:

3

Hello,

I'm not a java developer. But I'm currently taking a look at Android applications development so I'm doing a bit of nostalgy, doing some java again after not touching it for three years.

I'm looking forward 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 want 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 ?

+1  A: 

Yes - If the enum is X, use X.values(). See in this tutorial.

Little Bobby Tables
I tried that. But the library redefines the toString() method. So what I get is still the value and not the key.
Damien MATHIEU
@Damien: See the edit to my answer. Basically you're after name()
Jon Skeet
+3  A: 

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
}
Jon Skeet
.name() is exactly what I was looking for. Thank you.
Damien MATHIEU