Java Reference
In-Depth Information
1 // Print the contents of Collection c (using iterator directly)
2 public static <AnyType> void printCollection( Collection<AnyType> c )
3 {
4
figure 6.11
Print the contents of
any Collection.
Iterator<AnyType> itr = c.iterator( );
while( itr.hasNext( ) )
5
System.out.print( itr.next( ) + " " );
6
System.out.println( );
7
8 }
9
10 // Print the contents of Collection c (using enhanced for loop)
11 public static <AnyType> void printCollection( Collection<AnyType> c )
12 {
13
for( AnyType val : c )
System.out.print( val + " " );
14
System.out.println( );
15
16 }
the enhanced for loop to work.) As an example of using the Iterator , the
routines in Figure 6.11 print each element in any container. If the container
is an ordered set, its elements are output in sorted order. The first implemen-
tation uses an iterator directly, and the second implementation uses an
enhanced for loop. The enhanced for loop is simply a compiler substitution.
The compiler, in effect, generates the first version (with java.util.Iterator )
from the second.
generic algorithms
6.4
The Collections API provides a few general purpose algorithms that operate
on all of the containers. These are static methods in the Collections class (note
that this is a different class than the Collection interface). There are also some
static methods in the Arrays class that manipulate arrays (sorting, searching,
etc.). Most of those methods are overloaded—a generic version, and once for
each of the primitive types (except boolean ).
We examine only a few of the algorithms, with the intention of showing
the general ideas that pervade the Collections API, while documenting the
specific algorithms that will be used in Part Three.
The Collections
class contains a set
of static methods
that operate on
Collection objects.
Some of the algorithms make use of function objects. Consequently, the
material in Section 4.8 is an essential prerequisite to this section.
The material in
Section 4.8 is an
essential prerequi-
site to this section.
 
 
Search WWH ::




Custom Search