Java Reference
In-Depth Information
Using Generic Collections
Problem
safety, and without having to write downcasts when retrieving data from the collection.
Solution
Use Java's Generic Types mechanism, and declare the
Collection
with a “type parameter”
of the correct type. The type parameter name appears in angle brackets after the declaration
and instantiation. For example, to declare an
ArrayList
for holding
String
object referen-
ces:
List<String> myList = new ArrayList<String>();
Discussion
When you instantiate a
Collection
(or any other class using Generic Types), the class ap-
pears to be instantiated with the type given in angle brackets becoming the type of arguments
passed in, values returned, and so on.
Avoid Casting by Using Generics
provides some de-
tails on the implementation. As an example, consider the code in
Example 7-1
,
which creates
and uses an
ArrayList
specialized to contain
String
objects.
Example 7-1. ArrayListGenericDemo.java
public
public class
class
ArrayListGenericDemo
ArrayListGenericDemo
{
public
public static
void
main
(
String
[]
args
) {
ArrayList
<
String
>
data
=
new
static
void
new
ArrayList
<>();
data
.
add
(
"hello"
);
data
.
add
(
"goodbye"
);
// data.add(new Date()); This won't compile!
data
.
forEach
(
s
->
System
.
out
.
println
(
s
));
}
}
Generics, the references obtained from a
Collection
or
Iterator
would have to be down-