Member-only story
Effective Java! Use EnumMap instead of Ordinal Indexing
We again consider another special collection type that handles enum
s in an efficient manner. This time we consider EnumMap
s. 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]);
}