How to use typesafe enums in Java

Use typesafe enums to avoid the problems with traditional enumerated types

1 2 Page 2
Page 2 of 2
  • compareTo() compares the current constant with the constant passed as an argument to see which constant precedes the other constant in the enum and returns a value indicating their order. This method makes it possible to sort an array of unsorted constants.
  • getDeclaringClass() returns the java.lang.Class object corresponding to the current constant’s enum. For example, the Class object for Coin, in enum Coin { PENNY, NICKEL, DIME, QUARTER}, is returned when calling Coin.PENNY.getDeclaringClass(). (I’ll discuss Class in a future Java 101 article.)
  • name() returns the constant’s name. Unless overridden to return something more descriptive, toString() also returns the constant’s name.
  • ordinal() returns a zero-based ordinal, an integer that identifies the constant’s position in the typesafe enum. This integer is used by compareTo(). For example, in the previous Direction.NORTH.compareTo(Direction.SOUTH) expression, compareTo() returned -3 because NORTH has ordinal 0, SOUTH has ordinal 3, and 0 - 3 (which is what compareTo() in this context evaluates) equals -3.

Enum also provides the public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name) method for returning the constant from the specified typesafe enum with the specified name:

  • enumType identifies the Class object of the enum from which to return a constant.
  • name identifies the name of the constant to return.

For example, Coin penny = Enum.valueOf(Coin.class, "PENNY"); assigns the Coin constant whose name is PENNY to penny.

Finally, Enum’s Java documentation doesn’t include a values() method because the compiler manufactures this method while generating the typesafe enum’s class file.

You should get into the habit of using typesafe enums instead of traditional enumerated types. Also, get into the habit of using lambdas instead of anonymous inner classes. I discuss lambdas in my next Java 101 article.

This story, "How to use typesafe enums in Java" was originally published by JavaWorld.

Copyright © 2020 IDG Communications, Inc.

1 2 Page 2
Page 2 of 2