Java Reference
In-Depth Information
9
System.out.println( "All books:" );
10
11
// print all books in enum Book
12
for (
Book book : Book.values()
)
13
System.out.printf( "%-10s%-45s%s%n" , book,
14
book.getTitle() book.getCopyrightYear()
,
);
15
16
System.out.printf( "%nDisplay a range of enum constants:%n" );
17
18
// print first four books
19
for (Book book :
EnumSet.range(Book.JHTP, Book.CPPHTP)
)
20
System.out.printf( "%-10s%-45s%s%n" , book,
21
book.getTitle() book.getCopyrightYear()
,
);
22
}
23
} // end class EnumTest
All books:
JHTP Java How to Program 2015
CHTP C How to Program 2013
IW3HTP Internet & World Wide Web How to Program 2012
CPPHTP C++ How to Program 2014
VBHTP Visual Basic How to Program 2014
CSHARPHTP Visual C# How to Program 2014
Display a range of enum constants:
JHTP Java How to Program 2015
CHTP C How to Program 2013
IW3HTP Internet & World Wide Web How to Program 2012
CPPHTP C++ How to Program 2014
Fig. 8.11 | Testing enum type Book . (Part 2 of 2.)
Lines 19-21 use the static method range of class EnumSet (declared in package
java.util ) to display a range of the enum Book 's constants. Method range takes two
parameters—the first and the last enum constants in the range—and returns an EnumSet
that contains all the constants between these two constants, inclusive. For example, the
expression EnumSet.range(Book.JHTP , Book.CPPHTP) returns an EnumSet containing
Book.JHTP , Book.CHTP , Book.IW3HTP and Book.CPPHTP . The enhanced for statement can
be used with an EnumSet just as it can with an array, so lines 12-14 use it to display the
title and copyright year of every book in the EnumSet . Class EnumSet provides several other
static methods for creating sets of enum constants from the same enum type.
Common Programming Error 8.4
In an enum declaration, it's a syntax error to declare enum constants after the enum type's
constructors, fields and methods.
8.10 Garbage Collection
Every object uses system resources, such as memory. We need a disciplined way to give
resources back to the system when they're no longer needed; otherwise, “resource leaks”
might occur that would prevent resources from being reused by your program or possibly
 
 
Search WWH ::




Custom Search