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 thejava.lang.Class
object corresponding to the current constant’s enum. For example, theClass
object forCoin
, inenum Coin { PENNY, NICKEL, DIME, QUARTER}
, is returned when callingCoin.PENNY.getDeclaringClass()
. (I’ll discussClass
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 bycompareTo()
. For example, in the previousDirection.NORTH.compareTo(Direction.SOUTH)
expression,compareTo()
returned -3 becauseNORTH
has ordinal 0,SOUTH
has ordinal 3, and 0 - 3 (which is whatcompareTo()
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 theClass
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.