Java Reference
In-Depth Information
doing so is extra space. The most common place where using the array would
be useful is when the collection is being accessed several times or via nested
loops. If the array is being accessed only once, sequentially, it is unlikely that
using
toArray
will make things faster; it can make things slower while also
costing extra space.
One version of
toArray
returns the array in a type that is
Object[]
. The
other version allows the user to specify the exact type of the array by passing a
parameter containing the array (thus avoiding the costs of casting during the
subsequent manipulation). If the array is not large enough, a sufficiently large
array is returned instead; however, this should never be needed. The following
snippet shows how to obtain an array from a
Collection<String> coll
:
String [ ] theStrings = new String[ coll.size( ) ];
coll.toArray( theStrings );
At this point, the array can be manipulated via normal array indexing. The
one-parameter version of
toArray
is generally the one that you would want to
use because the runtime costs of casting are avoided.
Finally, the
iterator
method returns an
Iterator<AnyType>
, which can be
used to traverse the collection.
Figure 6.9 illustrates a specification of the
Collection
interface. The
actual
Collection
interface in
java.util
contains some additional methods,
but we will be content with this subset. By convention, all implementations
supply both a zero-parameter constructor that creates an empty collection
and a constructor that creates a collection that refers to the same elements as
another collection. This is basically a shallow-copy of a collection. How-
ever, there is no syntax in the language that forces the implementation of
these constructors.
The
Collection
interface extends
Iterable
, which means that the enhanced
for
loop can be applied to it. Recall that the
Iterable
interface requires the
implementation of an
iterator
method that returns a
java.util.Iterator
. The
compiler will expand the enhanced
for
loop with appropriate calls to methods
in
java.util.Iterator
. At line 41, we see the
iterator
method required by the
Iterable
interface. However, we remark that we are taking advantage of cova-
riant return types (Section 4.1.11), because the return type for the
iterator
method at line 41 is actually
weiss.util.Iterator
, which is our own class that
extends
java.util.Iterator
, and is shown in Section 6.3.2.
The Collections API also codifies the notion of an
optional interface
method
. For instance, suppose we want an immutable collection: Once it is
constructed, its state should never change. An immutable collection appears
incompatible with
Collection
, since
add
and
remove
do not make sense for
immutable collections.
Search WWH ::
Custom Search