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:

JavaScript

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:

JavaScript

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.

JavaScript

Mixing enum classes

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

JavaScript

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

JavaScript

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.

JavaScript

When run.

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement