Java Reference
In-Depth Information
Display 6.14
Some Methods Included with Every Enumerated Type
(part 2 of 2)
public int
ordinal( )
Returns the position of the calling value in the list of enumerated type values. The first position
is 0.
EXAMPLE
WorkDay.MONDAY.ordinal( )
returns
0
,
WorkDay.TUESDAY.ordinal( )
returns
1
, and so
forth. The enumerated type
WorkDay
is defined in Display 6.13.
public int
compareTo(
Any_Value_Of_The_Enumerated_Type
)
Returns a negative value if the calling object precedes the argument in the list of values, returns
0
if the calling object equals the argument, and returns a positive value if the argument precedes
the calling object.
EXAMPLE
WorkDay.TUESDAY.compareTo(WorkDay.THURSDAY)
returns a negative value. The type
WorkDay
is defined in Display 6.13.
public
EnumeratedType
[] values( )
Returns an array whose elements are the values of the enumerated type in the order in which
they are listed in the definition of the enumerated type.
EXAMPLE
See Display 6.15.
public static
EnumeratedType
valueOf(String name)
Returns the enumerated type value with the specified name. The string name must be an
exact match.
EXAMPLE
WorkDay.valueOf("THURSDAY")
returns
WorkDay.THURSDAY.
The type
WorkDay
is defined in
Display 6.13.
When comparing two variables (or constants) of an enumerated type, you can
use the
equals
method, but it is more common to instead use the
==
operator. For
example,
if
(meetingDay == availableDay)
System.out.println("Meeting will be on schedule.");
if
(meetingDay == WorkDay.THURSDAY)
System.out.println("Long weekend!");
With enumerated types, the
equals
method and the
==
operator are equivalent, but
the
==
operator has nicer syntax.