Java Reference
In-Depth Information
generics. Generic features pervade all the Collection Framework classes as well
as several other APIs in J2SE 5.0.
Suppose we have a list of strings:
List list
-
of
-
strings = new ArrayList ();
Without generics, we can insert any
Object
type into the list -
Strings
,
Integers
,anything. With generics, we declare the type of object the list is
allowed to contain at compile time. The syntax is as follows:
List
<
String
>
list
-
of
-
strings
=
new ArrayList
<
String
>
();
The
<
String
>
notation indicates that this particular
List
object is only allowed
to contain
String
types. Any attempt to add an
Integer
(autoboxed or not) or
anything else is disallowed at compile time:
list
-
of
-
strings.add (
"
this is legal
"
);
list
-
of
-
strings.add (new Integer (5)); // this is not allowed
list
-
of
-
strings.add (5); // neither is this
In the first illegal
add()
,weexplicitly wrap the 5 into an
Integer
.Even though
Integer
is an
Object
type, meaning it could be added to a plain
List
,itis
not permitted into the
List
<
String
>
object container. In the second attempt,
neither is the
int
5 permitted. The compiler errors you will see look like this:
Generics.java:7: cannot find symbol
symbol: method add (java.lang.Integer)
location: interface java.util.List
<
java.lang.String
>
list.add (new Integer (5));
^
Generics.java:8: cannot find symbol
symbol: method add (int)
location: interface java.util.List
<
java.lang.String
>
list.add (5);
^
The compiler is saying that it cannot find an
add()
method that takes an
Integer
type in the interface
java.util.List
<
java.lang.String
>
. Neither is
there an
add()
that takes an
int
.Byadding the generic type notation
<
String
>
(also known as a parameterized type) we have effectively created a new
List
interface that permits only
String
inserts. (Note that the second illegal
add()
did not autobox the
int
5 into an
Integer
. Doing so would not have worked
either since the first illegal attempt already demonstrated that adding an
Integer
is not permitted.)
Where generics becomes important and saves a lot of code is when iterating
over generic types and, in particular, in conjunction with autoboxing and unboxing
of primitive types. Recall that without generics we must cast returned
Object
types into the desired type during an iteration. That was with J2SE 1.4 and below.
Search WWH ::
Custom Search