Member-only story

Effective Java! Use EnumMap instead of Ordinal Indexing

Kyle Carter
2 min readJun 2, 2021

We again consider another special collection type that handles enums in an efficient manner. This time we consider EnumMaps. Let's consider some code that doesn't use an EnumMap and instead uses the ordinal built in function. As discussed in a previous chapter this is a function that should only be used by internal libraries and not by our code.

class PLant {
enum LifeCycle {ANNUAL, PERENNIAL, BIENNIAL }
final String name;
final LifeCycle lifeCycle;
Plant(String name, LifeCycle lifecycle) {
this.name = name;
this.lifecycle = lifecycle;
}
@Override
public String toString() {
return name;
}
}

Now let’s say we have a bunch of plants in our garden and we want to collect our plants together into groups of their lifecycles. To do this we create three sets and iterate through the garden and put the plants in the correct location.

// Using ordinal() to index into an array. Boo.
Set<Plant>[] plantsByLifecycle = (Set<Plant>[]) new Set[Plant.LifeCycle.values().length];
for (int i=0; i < plantsByLifeCycle.length; i++) {
plantsByLifeCycle[i] = new HashSet<>();
}
for (Plant p : garden) {
plantsByLifeCycle[p.lifeCycle.ordinal()].add(p);
}
for (int i = 0; i < plantsByLifeCycle.length; i++) {
System.out.printf("%s: %s%n", Plant.LifeCycle.values()[i], plantsByLifeCycle[i]);
}

--

--

Kyle Carter
Kyle Carter

Written by Kyle Carter

I'm a software architect that has a passion for software design and sharing with those around me.

No responses yet