When are enum values defined?

private static final int METRIC_COUNT = Metrics.values().length;

Can I do this?

Yes, you can. This is exactly the right way to cache the length and ensure it's only computed once.

I know the static variable will be determined at runtime (unless the value assigned to it were a literal value), so would the program be able to request the members of the Metrics enum at this point in execution?

Yep. As defined, METRIC_COUNT is also computed at runtime.


EnumSet

"compose" these metrics into a single object

essentially bit flags

Sounds like you need a bit-array, with a bit flipped for the presence/absence of each predefined enum value.

If so, no need to roll your own. Use EnumSet or EnumMap. These are special implementations of the Set and Map interfaces. These classes are extremely efficient because of their nature handling enums, taking very little memory and being very fast to execute.

Take for example the built-in DayOfWeek enum. Defines seven objects, one for each day of the week per ISO 8601 calendar.

Set< DayOfWeek > weekend = EnumSet.of( DayOfWeek.SATURDAY , DayOfWeek.SUNDAY ) ;

Use the convenient methods of Set such as contains.

boolean isTodayWeekend = weekend.contains( LocalDate.now().getDayOfWeek() ) ;

If you loop the elements of the set, they are promised to be provided in the order in which they are defined within the enum (their “natural” order). So, logically, an EnumSet should have been marked as a SortedSet, but mysteriously was not so marked. Nevertheless, you know the order. For example, looping EnumSet.allOf( DayOfWeek.class ) renders DayOfWeek.MONDAY first and DayOfWeek.SUNDAY last (per the ISO 8601 standard).

When Are Enum Values Defined?

The elements of an enum are defined at compile-time, and cannot be modified at runtime (unless you pull tricks with reflection). Each named variable is populated with an instance when the class is loaded. See Section 8.9, Enum Types of Java Language Specification.

If you define an enum Pet with DOG, CAT, and BIRD, then you know you will have exactly three instances at all times during runtime.

You can count the number of elements defined in an enum in at least two ways:

  • Calling the values method generated by the compiler for any enum, where you can ask the size of the resulting array, as you show in your Question.
    int countDows = DayOfWeek.values().length() ;
  • Calling Set::size after creating an EnumSet of all enum instances.
    int countDows = EnumSet.allOf( DayOfWeek.class ).size() ;

Tags:

Java