Skip to main content

Enum Collections if Possible

EnumMap over HashMap

If working with Enum's, and you need to store specific mappings, use EnumMap, as it gives a number of benefits over HashMap.

Under the Hood

EnumMap is at least, and likely to be more, performant than a standard HashMap due to the fact that:

  1. A quicker hash can be calculated due to the range of keys being known at compile time
  2. They are represented internally as arrays so operations always complete in constant amortized time - O(1)
  3. There is no opportunity for collisions within keys as each option is indexed by the enums values ordinal (index position in the declaration)

Instantiation

enum Status {
ACTIVE, DISABLED, UNRESPONSIVE
}

void enumTest() {
EnumMap<Status, String> statusMap = new EnumMap<>(Status.class);
statusMap.put(Status.ACTIVE, "www.active-route.com");
statusMap.put(Status.DISABLED, "www.disabled-route.com");
statusMap.put(Status.UNRESPONSIVE, "www.404.com");
}

Ordering

As EnumMap is an ordered map, the iteration order will be as defined by the order of the enum declarations.

for (Status status : statusMap.keySet()) {
System.out.println(status); // Prints ACTIVE, DISABLED, UNRESPONSIVE - in that order
}

EnumSet over HashSet

EnumSet's are a specialised implementation of the Set interface, and provides an extremely compact and efficient representation of the internal date. Similarly to EnumMap, it is at least as, and likely to be more, performant than a HashSet.

Represented internally as a bit vector/array, all operations (even bulk) execute in constant amortised time.

Under the Hood

If the enum selected for the EnumSet contains less than 65 values, a RegularEnumSet is initialised, which uses a long (64 bits) for its bit-vector representation. Otherwise, a JumboEnumSet is created, utilising a long array .

Instantiation

EnumSet<Status> statusMap = EnumSet.of(ACTIVE, DISABLED);

Ordering

Similarly to EnumMap, the order will be as defined by the order of the enum declarations.

for (Status status : EnumSet.of(Status.class).VALUES) {
System.out.println(status); // Prints ACTIVE, DISABLED, UNRESPONSIVE - in that order
}