Java Reference
In-Depth Information
▪ The type of the array argument determines the type of array returned.
▪ If the array is big enough (and you can ensure that it is by allocating the array based on
the
Collection
's
size()
method), then this array is filled and returned. If the array is
not big enough, a new array is allocated instead. If you provide an array and objects in
the
Collection
cannot be cast to this type, then you will get an
ArrayStoreException
.
Example 7-4. structure/ToArray.java
List
<
String
>
list
=
new
new
ArrayList
<>();
list
.
add
(
"Blobbo"
);
list
.
add
(
"Cracked"
);
list
.
add
(
"Dumbo"
);
// Convert a collection to Object[], which can store objects
// of any type.
Object
[]
ol
=
list
.
toArray
();
System
.
out
.
println
(
"Array of Object has length "
+
ol
.
length
);
String
[]
sl
= (
String
[])
list
.
toArray
(
new
new
String
[
0
]);
System
.
out
.
println
(
"Array of String has length "
+
sl
.
length
);
Rolling Your Own Iterator
Problem
You have your own data structure, but you want to publish the data as an
Iterator
to
provide generic access to it.
Solution
Write your own
Iterator
. Just implement (or provide an inner class that implements) the
Iterator
(or
Enumeration
) interface. For extra points, implement
Iterable
and your ob-
jects can be iterated with a “foreach” loop.