Home > other >  How to Create a List of Different Enum Classes
How to Create a List of Different Enum Classes

Time:12-31

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?

CodePudding user response:

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. And perhaps reflection.

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< Enum > myEnumClasses = List.of( Pet.class , Wild.class ) ;

Now we can perform your loop. (Maybe… I’ve not run the following line yet.)

for ( Enum e : myEnumClasses ) {
    System.out.println( List.of( e.values() ) );
}
  • Related