10.12.2012 Views

The Java Language Specification, Third Edition

The Java Language Specification, Third Edition

The Java Language Specification, Third Edition

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CLASSES Enums 8.9<br />

Note that the example can easily be refactored to work properly:<br />

enum Color {<br />

RED, GREEN, BLUE;<br />

static final Map colorMap =<br />

new HashMap();<br />

static {<br />

for (Color c : Color.values())<br />

colorMap.put(c.toString(), c);<br />

}<br />

}<br />

<strong>The</strong> refactored version is clearly correct, as static initialization occurs top to bottom.<br />

DISCUSSION<br />

Here is program with a nested enum declaration that uses an enhanced for loop to iterate<br />

over the constants in the enum:<br />

public class Example1 {<br />

public enum Season { WINTER, SPRING, SUMMER, FALL }<br />

public static void main(String[] args) {<br />

for (Season s : Season.values())<br />

System.out.println(s);<br />

}<br />

}<br />

Running this program produces the following output:<br />

WINTER<br />

SPRING<br />

SUMMER<br />

FALL<br />

Here is a program illustrating the use of EnumSet to work with subranges:<br />

import java.util.*;<br />

DRAFT<br />

public class Example2 {<br />

enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATUR-<br />

DAY, SUNDAY }<br />

}<br />

public static void main(String[] args) {<br />

System.out.print("Weekdays: ");<br />

for (Day d : EnumSet.range(Day.MONDAY, Day.FRIDAY))<br />

System.out.print(d + " ");<br />

System.out.println();<br />

}<br />

253

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!