Java Reference
In-Depth Information
type. The
java.lang.Enum
class defines a number of
final
methods that all
enum
types inherit. In addition, all
enum
types have two implicitly declared
static
methods:
values()
and
valueOf(String)
. The solution code demonstrates
these
static
methods and some of the more often used instance methods.
Most of these methods are fairly self-explantory, but you should keep the following
details in mind:
•
Each
enum
constant has an ordinal value representing its relative posi-
tion in the
enum
declaration. The first constant in the declaration is as-
signed an ordinal value of zero. The
ordinal()
method can be used
to retrieve an
enum
constant's ordinal value; however, it is not recom-
mended that applications be written to depend on this value for main-
tainability reasons.
•
The
name()
method and the default implementation of the
toString()
method both return a string representation of the
enum
constant (
toString()
actually calls
name()
). It is common for
toString()
to be overridden to provide a more user-friendly string
representation of the
enum
constant. For this reason, and for maintain-
ability reasons, it is recommended that
toString()
be used in prefer-
ence to
name()
.
•
When testing for equality, note that both the
equals()
method and
==
perform reference comparison. They can be used interchangeably.
However, it is recommended that
==
be used to take advantage of
compile-time type safety. This is illustrated in the solution code. Per-
forming
equals()
comparison with a
String
parameter, for ex-
ample, may allow the error to go unnoticed; it will compile, but it will
always return
false
. Conversely, attempting to compare an
enum
with
a
String
using the
==
comparison would result in an error at compile
time. When you have the choice of catching errors sooner (at compile
time) rather than later (at runtime), choose the former.
•
The implicitly declared static methods
values()
and
valueOf(String)
do not appear in the Java documentation or the
source code for the
java.lang.Enum
class. However, the Java Lan-
guage Specification does detail their required implementations. To sum-
marize these methods,
values()
returns an array containing the con-
stants of the
enum
, in the order they are declared. The