3.3 Iterating Over Enums
Ever been given a class with
lousy documentation, no source code, and
little instruction on its use? Welcome to the loosely knit organization of
real-world programmers. In many cases, you can resort to reflection to
figure out what a class has to offer in lieu of source code, and of course
JavaDoc is always helpful. In the case of enumerated types, though,
there's a nice built-in
feature: the values( ) method. This method provides
access to all of the types within an enum.
3.3.1 How do I do that?
Invoking the values( ) method on an enum returns an array of all the
values in the type:
This is a nice way to get a quick dump of all the allowed values for a
public void listGradeValues(PrintStream out) throws IOException {
Grade[] gradeValues = Grade.values( );
for (Grade g : Grade.values( )) {
out.println("Allowed value: '" + g + "'");
}
}
particular enum:
NOTERun this sample
run-ch03:
[echo] Running Chapter 3 examples from Java 1.5: A Developer's Notebook
[echo] Running GradeTester...
[java] Allowed value: 'A'
[java] Allowed value: 'B'
[java] Allowed value: 'C'
[java] Allowed value: 'D'
[java] Allowed value: 'F'
[java] Allowed value: 'INCOMPLETE'
with the Ant
target "run-ch03".
3.3.2 What just happened?
First, note that type-safety is employed. values( ) doesn't return an
array of String valuesinstead it returns an array of Grade instances. In
the out.println( ) statement, each Grade has its toString( ) method executed, which in turn does provide a String name for the value. At no
point are you working with integer constants or even String valuesthe
Grade object hides all these implementation details from you, and allows
strict compile-time checking.
3.3.3 What about...
...using a for/in loop? Well, you're ahead of mefor/in isn't covered
until Chapter 7. Still, for those of you who are curious, you can indeed
perform the same iteration with Tiger's new for/in capabilities:
// for/in loop
for (Grade g : grade.values( )) {
out.println("Allowed value: '" + g + "'");
}