Generic Types
Generic types and methods are the defining new feature of Java 5.0. A
generic type
is
defined using one or more type
variables
and has one or more methods that use a type variable as a placeholder
for an argument or return type. For example, the type
java.util.List<E> is a generic type: a list
that holds elements of some type represented by the placeholder
E. This type has a method named
add(), declared to take an argument of type
E, and a method named get(),
declared to return a value of type E.
In order to use a generic type like this,
you specify actual types for the type variable (or variables),
producing a parameterized
type
such as
List<String>.[1] The reason to specify this extra type information is that
the compiler can provide much stronger compile-time type checking for
you, increasing the type safety of your programs. This type checking
prevents you from adding a String[], for example,
to a List that is intended to hold only
String objects. Also, the additional type
information enables the compiler to do some casting for you. The
compiler knows that the get( ) method of a
List<String> (for example) returns a
String object: you are no longer required to cast
a return value of type Object to a
String.
The
collections
classes of the java.util package have been made generic in Java 5.0, and you will probably use them frequently in your programs. Typesafe collections are the canonical use case for generic types. Even if you never define generic types of your ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access