Java Reference
In-Depth Information
The reference list and the object it refers to are both of type ArrayList<Double> .
However, the following statement is not valid:
ArrayList<Number> notvalid = new ArrayList<Double>();//doesn't compile
Even though Double is a child of Number , the compiler complains that
ArrayList<Double> is incompatible with ArrayList<Number> . An ArrayList<Number>
reference can only point to an ArrayList object whose generic is a Number . If you want
a reference that can refer to an ArrayList whose generic is any Number (including subclasses
of Number ), you need to use the wildcard:
ArrayList<? extends Number> list2 = new ArrayList<Double>();
The generic <? extends Number> declares list2 as a reference to an ArrayList object
whose generic is Number or any subclass of Number .
The following statements are also valid:
ArrayList<? extends Number> list3 = new ArrayList<Integer>();
List<? extends Number> list4 = new Stack<Float>();
The list3 reference is valid because Integer is a child of Number . The list4 reference is
valid because both Float is a child of Number and Stack implements List .
Lower-Bound Wildcards
Similar to using the extends keyword for creating an upper-bound wildcard, you can
use the super keyword to create a lower-bound wildcard with a wildcard generic. For
example, the following statement declares a generic type that must be an IOException or
parent of IOException :
<? super IOException>
Using this generic type, see if you can determine whether or not the following statements
are valid declarations:
6. ArrayList<? super IOException> alist1 = new ArrayList<Exception>();
7. ArrayList<? super IOException> alist2 =
new ArrayList<IOException>();
8. ArrayList<? super IOException> alist3 =
new ArrayList<FileNotFoundException>();
Line 6 is valid because <Exception> is a supertype of the generic <? super
IOException> and Exception is a parent class of IOException . Line 7 is valid because the
lower-bound generic <? super IOException> includes the IOException class. Line 8 does
Search WWH ::




Custom Search