106

I'm trying to find a way to iterate through an enum's values while using generics. Not sure how to do this or if it is possible.

The following code illustrates what I want to do. Note that the code T.values() is not valid in the following code.

public class Filter<T> {
    private List<T> availableOptions = new ArrayList<T>();
    private T selectedOption;

    public Filter(T selectedOption) {
        this.selectedOption = selectedOption;
        for (T option : T.values()) {  // INVALID CODE
            availableOptions.add(option);
        }
    }
}

Here is how I would instantiate a Filter object:

Filter<TimePeriod> filter = new Filter<TimePeriod>(TimePeriod.ALL);

The enum is defined as follows:

public enum TimePeriod {
    ALL("All"), 
    FUTURE("Future"), 
    NEXT7DAYS("Next 7 Days"), 
    NEXT14DAYS("Next 14 Days"), 
    NEXT30DAYS("Next 30 Days"), 
    PAST("Past"),
    LAST7DAYS("Last 7 Days"), 
    LAST14DAYS("Last 14 Days"),
    LAST30DAYS("Last 30 Days"); 

    private final String name;

    private TimePeriod(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return name;
    }
}

I realize it might not make sense to copy a enum's values to a list, but I'm using a library that needs a list of values as input and won't work with enums.


EDIT 2/5/2010:

Most of the answers proposed are very similar and suggest doing something like this:

class Filter<T extends Enum<T>> {
    private List<T> availableOptions = new ArrayList<T>();
    private T selectedOption;

    public Filter(T selectedOption) {
        Class<T> clazz = (Class<T>) selectedOption.getClass();
        for (T option : clazz.getEnumConstants()) {
            availableOptions.add(option);
        }
    }
}

This would work great if I can be sure that selectedOption has a non-null value. Unfortunately, in my use case, this value is often null, as there is a public Filter() no-arg constructor as well. This means I can't do a selectedOption.getClass() without getting an NPE. This filter class manages a list of available options which of the options is selected. When nothing is selected, selectedOption is null.

The only thing I can think to solve this is to actually pass in a Class in the constructor. So something like this:

class Filter<T extends Enum<T>> {
    private List<T> availableOptions = new ArrayList<T>();
    private T selectedOption;

    public Filter(Class<T> clazz) {
        this(clazz,null);
    }

    public Filter(Class<T> clazz, T selectedOption) {
        this.selectedOption = selectedOption;
        for (T option : clazz.getEnumConstants()) {
            availableOptions.add(option);
        }
    }
}

Any ideas how to do this without needing an extra Class parameter in the constructors?

Tauren
  • 26,795
  • 42
  • 131
  • 167
  • 3
    The `getClass` code will also fail if the enum constant is an anonymous subclass ([example](https://ideone.com/ccjW7w)). [`getDeclaringClass`](http://docs.oracle.com/javase/8/docs/api/java/lang/Enum.html#getDeclaringClass--) should be used instead. – Radiodef Sep 11 '17 at 17:22

10 Answers10

156

This is a hard problem indeed. One of the things you need to do is tell java that you are using an enum. This is by stating that you extend the Enum class for your generics. However this class doesn't have the values() function. So you have to take the class for which you can get the values.

The following example should help you fix your problem:

public <T extends Enum<T>> void enumValues(Class<T> enumType) {
        for (T c : enumType.getEnumConstants()) {
             System.out.println(c.name());
        }
}
Thirler
  • 20,239
  • 14
  • 63
  • 92
  • 1
    Isn't the c.name() returning the name of the enum item ? How about returning its value ? Say, for a QUIZ("quizzie") item, returning the "quizzie" and not the QUIZ. – Stephane Nov 24 '15 at 09:44
  • 1
    For that you would need to have a method on the enum that returns the value say: `getFriendlyName()`. Then you'd have to add an interface to your enum and then adapt the generics above to require both an enum AND the interface for type `T`. The function then becomes something like: `public & EnumWithFriendlyName> void friendlyEnumValues(Class enumType)` – Thirler Nov 24 '15 at 09:50
  • Can I get some detail as to how to write the interface for type T or any link where I can find an example because I am looking to retrieve values. – Sonali Gupta Jun 01 '21 at 05:55
  • @SonaliGupta it's the same mechanism as any other interface. You define an interface with your function `getFriendlyName()`, then in the enum you implement the interface using 'implements EnumWithFriendlyName`' and your function that wants to use the enum's interface functions you do what I show in my previous comment. – Thirler Jun 02 '21 at 08:18
  • why does the Enum class have the values() method? doesnt every enum have it and extends this class? whats the reasoning behind not putting it there? – peter Oct 16 '22 at 07:34
23

Another option is to use EnumSet:

class PrintEnumConsants {

    static <E extends Enum <E>> void foo(Class<E> elemType) {
        for (E e : java.util.EnumSet.allOf(elemType)) {
            System.out.println(e);
        }
    }

    enum Color{RED,YELLOW,BLUE};
    public static void main(String[] args) {
        foo(Color.class);
    } 

}
Miserable Variable
  • 28,432
  • 15
  • 72
  • 133
8

For completeness, JDK8 gives us a relatively clean and more concise way of achieving this without the need to use the synthethic values() in Enum class:

Given a simple enum:

private enum TestEnum {
    A,
    B,
    C
}

And a test client:

@Test
public void testAllValues() {
    System.out.println(collectAllEnumValues(TestEnum.class));
}

This will print {A, B, C}:

public static <T extends Enum<T>> String collectAllEnumValues(Class<T> clazz) {
    return EnumSet.allOf(clazz).stream()
            .map(Enum::name)
            .collect(Collectors.joining(", " , "\"{", "}\""));
}

Code can be trivially adapted to retrieve different elements or to collect in a different way.

quantum
  • 3,000
  • 5
  • 41
  • 56
5

Using an unsafe cast:

class Filter<T extends Enum<T>> {
    private List<T> availableOptions = new ArrayList<T>();
    private T selectedOption;

    public Filter(T selectedOption) {
        Class<T> clazz = (Class<T>) selectedOption.getClass();
        for (T option : clazz.getEnumConstants()) {
            availableOptions.add(option);
        }
    }
}
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • `getClass` will fail if the enum constant is an anonymous subclass ([example](https://ideone.com/ccjW7w)). [`getDeclaringClass`](http://docs.oracle.com/javase/8/docs/api/java/lang/Enum.html#getDeclaringClass--) should be used instead. – Radiodef Sep 11 '17 at 17:20
1

If you are sure that selectedOption of the constructor Filter(T selectedOption) is not null. You can use reflection. Like this.

public class Filter<T> {
    private List<T> availableOptions = new ArrayList<T>();
    private T selectedOption;

    public Filter(T selectedOption) {
        this.selectedOption = selectedOption;
        for (T option : this.selectedOption.getClass().getEnumConstants()) {  // INVALID CODE
            availableOptions.add(option);
        }
    }
}

Hope this helps.

NawaMan
  • 25,129
  • 10
  • 51
  • 77
1

If you declare Filter as

public class Filter<T extends Iterable>

then

import java.util.Iterator;

public enum TimePeriod implements Iterable {
    ALL("All"),
    FUTURE("Future"),
    NEXT7DAYS("Next 7 Days"),
    NEXT14DAYS("Next 14 Days"),
    NEXT30DAYS("Next 30 Days"),
    PAST("Past"),
    LAST7DAYS("Last 7 Days"),
    LAST14DAYS("Last 14 Days"),
    LAST30DAYS("Last 30 Days");

    private final String name;

    private TimePeriod(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return name;
    }

    public Iterator<TimePeriod> iterator() {
        return new Iterator<TimePeriod>() {

            private int index;

            @Override
            public boolean hasNext() {
                return index < LAST30DAYS.ordinal();
            }

            @Override
            public TimePeriod next() {
                switch(index++) {
                    case    0   : return        ALL;
                    case    1   : return        FUTURE;
                    case    2   : return        NEXT7DAYS;
                    case    3   : return        NEXT14DAYS;
                    case    4   : return        NEXT30DAYS;
                    case    5   : return        PAST;
                    case    6   : return        LAST7DAYS;
                    case    7   : return        LAST14DAYS;
                    case    8   : return        LAST30DAYS;
                    default: throw new IllegalStateException();
                }
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException();
            }
        };
    }
}

And usage is quite easy:

public class Filter<T> {
    private List<T> availableOptions = new ArrayList<T>();
    private T selectedOption;

    public Filter(T selectedOption) {
        this.selectedOption = selectedOption;
        Iterator<TimePeriod> it = selectedOption.iterator();
        while(it.hasNext()) {
            availableOptions.add(it.next());
        }
    }
}
Boris Pavlović
  • 63,078
  • 28
  • 122
  • 148
  • Interesting approach. I think this would work without needing to have Class declared. However, I'd prefer to not have to change all of my enums, so I'm leaning toward a different method. – Tauren Feb 05 '10 at 22:40
1

To get the value of the generic enumeration:

  protected Set<String> enum2set(Class<? extends Enum<?>> e) {
    Enum<?>[] enums = e.getEnumConstants();
    String[] names = new String[enums.length];
    for (int i = 0; i < enums.length; i++) {
      names[i] = enums[i].toString();
    }
    return new HashSet<String>(Arrays.asList(names));
  }

Note in the above method the call to the toString() method.

And then define the enumeration with such a toString() method.

public enum MyNameEnum {

  MR("John"), MRS("Anna");

  private String name;

  private MyNameEnum(String name) {
    this.name = name;
  }

  public String toString() {
    return this.name;
  }

}
Stephane
  • 11,836
  • 25
  • 112
  • 175
1

I did it like this

    protected List<String> enumToList(Class<? extends Enum<?>> e) {
            Enum<?>[] enums = e.getEnumConstants();
            return Arrays.asList(enums).stream()
                   .map(name -> name.toString())
                   .collect(Collectors.toList());
        }
Pradeep Sreeram
  • 368
  • 4
  • 19
0

The root problem is that you need to convert an array to a list, right? You can do this, by using a specific type (TimePeriod instead of T), and the following code.

So use something like this:

List<TimePeriod> list = new ArrayList<TimePeriod>();
list.addAll(Arrays.asList(sizes));

Now you can pass list into any method that wants a list.

Steve McLeod
  • 51,737
  • 47
  • 128
  • 184
0

Here below an example of a wrapper class around an Enum. Is a little bit weird bu is what i need :

public class W2UIEnum<T extends Enum<T> & Resumable> {

public String id;
public String caption;

public W2UIEnum(ApplicationContext appContext, T t) {
    this.id = t.getResume();
    this.caption = I18N.singleInstance.getI18nString(t.name(), "enum_"
            + t.getClass().getSimpleName().substring(0, 1).toLowerCase()
            + t.getClass().getSimpleName().substring(1,
                    t.getClass().getSimpleName().length()), appContext
            .getLocale());
}

public static <T extends Enum<T> & Resumable> List<W2UIEnum<T>> values(
        ApplicationContext appContext, Class<T> enumType) {
    List<W2UIEnum<T>> statusList = new ArrayList<W2UIEnum<T>>();
    for (T status : enumType.getEnumConstants()) {
        statusList.add(new W2UIEnum(appContext, status));
    }
    return statusList;
}

}

Benjamin Fuentes
  • 674
  • 9
  • 22