Java Reference
In-Depth Information
I.3 Processing Enumerated Values Using
a Foreach Loop
Each enumerated type has a static method
values()
that returns all enumerated values for
the type in an array. For example,
Day[] days = Day.values();
You can use a regular for loop in (a) or a foreach loop in (b) to process all the values in
the array.
for
(
int
i =
0
; i < days.length; i++)
System.out.println(days[i]);
for
(Day day: days)
System.out.println(day);
Equivalent
(a)
(b)
I.4 Enumerated Types with Data Fields,
Constructors, and Methods
The simple enumerated types introduced in the preceding section define a type with a list of
enumerated values. You can also define an enumerate type with data fields, constructors, and
methods, as shown in Listing I.3.
L
ISTING
I.3
TrafficLight.java
1
public enum
TrafficLight {
2 RED (
"Please stop"
), GREEN (
"Please go"
),
3 YELLOW (
"Please caution"
);
4
5
private
String description;
6
7
private
TrafficLight(String description) {
8
this
.description = description;
9 }
10
11
public
String getDescription() {
12
return
description;
13 }
14 }
The enumerated values are defined in lines 2-3. The value declaration must be the first
statement in the type declaration. A data field named
description
is declared in line 5 to
describe an enumerated value. The constructor
TrafficLight
is declared in lines 7-9. The
constructor is invoked whenever an enumerated value is accessed. The enumerated value's
argument is passed to the constructor, which is then assigned to
description
.
Listing I.4 gives a test program to use
TrafficLight
.
L
ISTING
I.4
TestTrafficLight.java
1
public class
TestTrafficLight {
2
public static void
main(String[] args) {
3 TrafficLight light = TrafficLight.RED;
4 System.out.println(light.getDescription());
5 }
6 }
Search WWH ::
Custom Search