Java Reference
In-Depth Information
1.13. Generic Types
Classes and interfaces can be declared to be
generic types.
A generic
class or interface represents a family of related types. For example, in
interface List<T> {
// ... methods of List ...
}
List<T>
(read as "list of
T
") declares a generic list that can be used for
any non-primitive type
T
. You could use such a declaration to have a list
of
Point
objects (
List<Point>
), a list of
String
objects (
List<String>
), a list
of
Integer
objects (
List<Integer>
), and so on. In contrast to a
raw
List
,
which can hold any kind of
Object
, a
List<String>
is known to hold only
String
objects, and this fact is guaranteed at compile timeif you try to
add a plain
Object
, for example, you'll get a compile-time error.
Consider the
Lookup
interface from the previous section, it could be de-
clared in a generic form:
interface Lookup<T> {
T find(String name);
}
Now, rather than returning
Object
, the
find
method returns a
T
, whatever
T
may be. We could then declare a class for looking up integers, for ex-
ample:
class IntegerLookup implements Lookup<Integer> {
private String[] names;
private Integer[] values;
public Integer find(String name) {
for (int i = 0; i < names.length; i++) {