Why doesn't Java provide access to the enum class objects for EnumSet and EnumMap?

155 Views Asked by At

EnumSet has an private field for the value class. Why not provide public access?

Also, EnumMap has private fields for key and value classes. Same question.

For non-empty sets/maps, it is possible iterate the first element and extract class from a non-null value. However, for empty sets/maps, this is not possible.

2

There are 2 best solutions below

0
On

The reason there is no getter-method for the member class of an EnumSet nor for the key class of EnumMap is that in order to use these classes effectively, the static type is generally known and used by the programmer, and the type's Class can easily be derived from the type name using a class literal.

For example, consider the following enum:

enum Direction { NORTH, EAST, SOUTH, WEST }

You'd use it like this:

Set<Direction> wittsEnd = EnumSet.of(NORTH, EAST, SOUTH); // hint: don't go west

To add, remove, or check membership in this set, we generally have a Direction instance. If we want to create a new set or derive one from an existing set, we'd declare a variable of type Set<Direction>. If we want the Class object corresponding to the enum type, we just use Direction.class. Thus there is generally no need to get the Class object out of the EnumSet itself.

Similar reasoning applies to EnumMap.

I suppose there might be some case out there where one has an instance of an EnumSet<?> and you want to create a set of all or none of the enum values, which requires the Class object for a type not known at compile time. Such a case would seem to be quite contrived. For such cases, though, one could use this equally contrived technique (i.e., hack) to get the enum class for some unknown EnumSet s:

Class<? extends Enum<?>> enumClass =
    EnumSet.copyOf(s).addAll(EnumSet.complementOf(s)).iterator().next().getClass();

A similar technique could probably be used to get the key class of an EnumMap.

0
On

EnumSet has an private field for the value class. Why not provide public access?

I cannot think of a technical reason not to. However, I also can't think of a compelling use-case that requires it.

But ultimately, the answer for your Questions is that it was a decision made by the Java designers, and only they are in a position to explain the actual reasoning for the decisions.