Skip to content
Advertisement

How to Create a List of Different Enum Classes

I’d like to create a list of different Enum classes and be able to access the values of these enums in the list. For instance, consider two Enums:

enum Enum1 {
  ENUM1_VALUE_1, ENUM1_VALUE_2;
}

enum Enum2 {
  ENUM2_VALUE_1, ENUM2_VALUE_2;
}

I’d like to construct a list of Enum1 and Enum2 such that I can print the values of Enum1 and Enum2.

It would look something like this, but this obviously doesn’t compile:

List<Enum> enumList = Arrays.asList(Enum1, Enum2);
for (Enum enumEntry: enumList) {
    System.out.println(enumList.values());
}

Any ideas?

Advertisement

Answer

Mixing enum objects

Have both classes implement the same interface, with any methods you need.

Then create your list containing objects of that interface rather than of either enum class.

Tip: As of Java 16, interfaces, enum, and records can be defined locally.

interface Animal {}

enum Pet implements Animal { DOG, CAT ; }
enum Wild implements Animal { LION , ORCA ; }

List< Animal > felines = List.of( Pet.CAT , Wild.LION ) ;

Mixing enum classes

If the class of the enum is what you want to collect, use the Class class.

List< Class > myEnumClasses = List.of( Pet.class , Wild.class ) ;

Enums in Java implicitly extend the Enum class. So we can be more specific with our type of list.

List < Class < ? extends Enum > > myEnumClasses = List.of( Pet.class , Wild.class );

myEnumClasses.toString(): [class demo.App$1Pet, class demo.App$1Wild]

Regarding the last part, your ultimate goal of looping the Enum classes to invoke the implicit Enum method public static T[] values() on each… Use a special method found on the Class class: getEnumConstants. That method returns an array of the enum’s objects.

For convenience, we can pass that array to List.of to easily generate a textual representation of the enum objects by calling List#toString.

for ( Class < ? extends Enum > e : myEnumClasses )
{
    System.out.println( "e = " + e );
    System.out.println( List.of( e.getEnumConstants() ) );  // Pass the array T[] to `List.of` for convenient printing.
}

When run.

e = class demo.App$1Pet
[DOG, CAT]
e = class demo.App$1Wild
[LION, ORCA]
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement