The need for generic types stems mainly from the implementation
and use of collections, like the ones in the Java Collections framework.
Programmers often want to specify that a collection contains elements of
a certain type, such as a list of integral values or a list of strings.
The Collections framework in non-generic Java did not offer any homogenous
collections of elements of the same type. Instead, all collections
references and for that reason they were potentially
heterogenous, that is, a mix of objects of different types. This
was also visible in the collection APIs: the non-generic collections accepted
objects of arbitrary type for insertion into the collection and returned
reference when an element was retrieved from the collection
in Java 1.4).
In non-generic Java, homogenous collections of elements had required
implementation of different classes, such as a class
and a class
for holding integral values and strings
respectively. Naturally, implementing a separate collection class for
every conceivable element type is neither feasible nor desirable.
A more reasonable goal is to have a single implementation of the collection
class and use it to hold elements of different types. In other words,
rather than implementing a class
we want to have one generic implementation
that can be easily
used in either case, as well as in other unforeseen cases.
This is what generics are for: the implementation of one generic class
can be instantiated for a variety of types. There is one generic
in the generic collections framework (see package
in Java 5.0). It permits specification of
etc. each of which is a homogenous collection of integral values, strings,
etc. In generic Java, the generic class
is a so-called
that has a type parameter. Uses such as
of the generic class, where the type parameter
is replaced by the concrete type arguments
The use of the Java generics language features were initially motivated
by the need to have a mechanism for efficient implementation of homogenous
collections, but the language feature is not restricted to collections.
The J2SE 5.0 platform libraries contains numerous examples of generic types
and methods that have nothing to do with collections. Examples are
the weak and soft references in package
which are special purpose references to objects of a particular type represented
by a type parameter. Or the interface
which represents a task and has a
method that returns a result
of a particular type represented by a type parameter. Even class
is a generic class since Java 5.0, whose type parameter denotes the type