Chapter 16. Generics Framework
The Generics Framework, introduced in Java SE 5.0, provides support that allows for the parameterization of types.
The benefit of generics is the significant reduction in the amount of code that needs to be written when developing a library. Another benefit is the elimination of casting in many situations.
The classes of the Collections Framework, the class Class
, and other Java libraries have been updated
to include generics.
See Java Generics and Collections by Maurice Naftalin and Philip Wadler (O’Reilly, 2006) for comprehensive coverage of the Generics Framework.
Generic Classes and Interfaces
Generic classes and interfaces parameterize types by adding a type
parameter within angular brackets (i.e., <T>
). The type is instantiated at the
place of the brackets.
Once instantiated, the generic parameter type is applied throughout
the class for methods that have the same type specified. In the following
example, the add()
and get()
methods use the parameterized type as
their parameter argument and return types, respectively:
public
interface
List
<
E
>
extends
Collection
<
E
>{
public
boolean
add
(
E
e
);
E
get
(
int
index
);
}
When a variable of a parameterized type is declared, a concrete type
(i.e., <Integer>)
is specified to
be used in place of the type parameter (i.e., <E>
).
Subsequently, the need to cast when retrieving elements from things such as collections would be eliminated:
// Collection List/ArrayList with Generics
List
<
Integer
>
iList
=
new
ArrayList
<
Integer ...
Get Java 7 Pocket Guide, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.