Java Reference
In-Depth Information
final
. In some situations (discussed later), the compiler cannot
declare it as
final
as it has done in the sample code for the
Severity
class.
•
An enum type is implicitly
values()
and
valueOf()
, to every enum type. The
values()
method returns the array of enum constants in the same order they are declared in
the enum type. You have seen the use of the
values()
method in Listing 18-2. The
valueOf()
method is used to get the instance of an enum type using the constant name as a string. For
example,
Severity.valueOf("LOW")
will return the
Severity.LOW
constant. The
valueOf()
method facilitates reverse lookup—from a string value to an enum type value.
•
The compiler adds two static methods,
•
The
Enum
class implements the
java.lang.Comparable
and
java.io.Serializable
interfaces.
This means instances of every enum type can be compared and serialized. The
Enum
class
makes sure that during the deserialization process no other instances of an enum type are
created than the ones declared as the enum constants. You can use the
compareTo()
method
to determine if one enum constant is declared before or after another enum constant. Note
that you can also determine the order of two enum constants by comparing their ordinals.
The
compareTo()
method does the same, with one more check, that the enum constants being
compared must be of the same enum type. The following code snippet shows how to compare
two enum constants:
Severity s1 = Severity.LOW;
Severity s2 = Severity.HIGH;
// s1.compareTo(s2) returns s1.ordinal() - s2.ordinal()
int diff = s1.compareTo(s2);
if (diff > 0) {
System.out.println(s1 + " occurs after " + s2);
}
else {
System.out.println(s1 + " occurs before " + s2);
}
Using Enum Types in switch Statements
You can use enum types in switch statements. When the switch expression is of an enum type, all case labels must be
unqualified enum constants of the same enum type. The switch statement deduces the enum type name from the type
of its expression. You may include a default label.
The following is a revised version of the
DefectUtil
class using a switch statement. Now you do not need to handle
the exceptional case of receiving a
null
value in the
severity
parameter inside
getProjectedTurnaroundDays()
method. If the enum expression of the switch statement evaluates to
null
, it throws a
NullPointerException
.
// DefectUtil.java
package com.jdojo.enums;
public class DefectUtil {
public static int getProjectedTurnaroundDays(Severity severity) {
int days = 0;
switch (severity) {
// Must use the unqualified name LOW, not Severity.LOW
case LOW:
days = 30;
break;