Java Reference
In-Depth Information
List
of
Integers
. A variable,
aList
, of the parameterized type
List<In-
teger>
is declared and then initialized with the reference obtained from the instanti-
ation of the parameterized type,
LinkedList<Integer>
(also called a “concrete
parameterized type”):
List<Integer> aList = new LinkedList<Integer>();
Now that you've parameterized these types to restrict the element type to
In-
tegers
, the
List add(E e)
method becomes:
boolean add(Integer e);
If you try to add anything other than an
Integer
to
aList
, the compiler will
generate an error:
aList.add(new Integer(121));
aList.add(42); // 42 is the same as new Integer(42),
due to autoboxing.
aList.add("Java"); // won't compile, wrong type
It's important to note that it's the reference type that is checked at compile time, so
the following will also result in a compiler error:
Number aNum = new Integer("7");
aList.add(aNum); // won't compile, wrong type
This is a compile error because
aNum
could reference any
Number
object. If the
compiler were to allow this, you could end up with a set that contains
Doubles
,
Floats
, and so on, which would violate the
Integer
parameter constraint you spe-
cified when you created
aList
. Of course, a simple type cast could get you around the
compiler error, but this would surely cause unintended consequences when casting
between incompatible
Number
objects. Generics were designed to reduce the amount
of explicit type casting you have to do in your code, so if you find yourself using expli-
cit type casting when using methods of parameterized types, this is a clue of potentially
dangerous code.
aList.add((Integer)aNum); // compiles, but don't do this.