Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write a generic for loop for a Java Enum?

Is there a way to write a generic loop to iterate over an arbitrary Enum? For example:

public static void putItemsInListBox(Enum enum, ListBox listbox){
    for(Enum e : enum.values(){
        listBox.addItem(e.toString(), String.valueOf(e.ordinal());
    }
}

You can not do the above, because the Enum class does not have a method called values() like the implemented Enum classes. The above for loop works fine for a class that is defined as an enum.

like image 392
Nick Avatar asked Feb 04 '10 22:02

Nick


2 Answers

It works exactly the same way as if the Class is passed:

public static <E extends Enum<?>> void iterateOverEnumsByInstance(E e)
{
    iterateOverEnumsByClass(e.getClass());
}

public static <E extends Enum<?>> void iterateOverEnumsByClass(Class<E> c)
{
    for (E o: c.getEnumConstants()) {
        System.out.println(o + " " + o.ordinal());
    }
}

Usage:

enum ABC { A, B, C }
...
iterateOverEnumsByClass(ABC.class);
iterateOverEnumsByInstance(ABC.A);
like image 61
axtavt Avatar answered Nov 02 '22 12:11

axtavt


This is cheap, but should work (at least according to my testing):

public static <T extends Enum<T>> void putItemsInListBox(Class<T> cls, ListBox listbox) {
    for (T item : EnumSet.allOf(cls))
        listbox.addItem(item.toString(), String.valueOf(item.ordinal()));
}

This works because EnumSet has special magical access to non-public members of Enum, which allows it to enumerate the enum's values despite the lack of a values method.

like image 39
Chris Jester-Young Avatar answered Nov 02 '22 11:11

Chris Jester-Young