Sunday, August 20, 2006

Iterating Over Enum With Generic Method

Generic methods in Java 5 are nice, but sometimes it's good to have examples to better understand what is going on.

The following generic method iterates over an enum type and retrieves its values (ordinals, i.e. their underlying integer value) and their names:
protected void addType(Class clazz, Enum<?>[] enumValues) {
List<SelectItem> selectItems = new ArrayList<SelectItem>();
for(Enum<?> value : enumValues) {
SelectItem item = new SelectItem(value.ordinal(),,;
itemLists.put(clazz, selectItems);
The invocation of this method might be:
addType(RoleType.class, RoleType.values());
In this example RoleType is defined as a enum with one or more values.

Another option would have been to declare the method as:
protected <T extends Enum<T>> void addType(Class clazz, T[] enumValues) {...}
However, I decided that the code would look harder to read, so I used the wildcard version instead. Let me know if this example was helpful.

No comments: