Java Reference
In-Depth Information
dList = new LinkedList<Integer>();
dList = new LinkedList<Number>();
dList = new LinkedList<Object>();
So, you see that Integer is the lower bound. This lower bound now places a re-
striction on retrieving elements from the list. Because dList can hold a reference to
any one of the previous parameterized types, the compiler would not be able to enforce
type safety if an assumption were made about the type of the element being retrieved.
Therefore, the compiler must not allow calls to get() on a collection type that is
parameterized with ? super , and the following would result in a compiler error:
Integer n = dList.get(0); // get() not allowed;
dList.get(0) could be a Number or Object
However, now you can add elements to the list, but the lower bound, Integer ,
still applies. Only Integers can be added because Integer is compatible with
Number and Object :
dList.add(new Integer(5)); // OK
Number dNum = new Double(7);
dList.add(dNum); // won't compile; dList could be
LinkedList<Integer>
You will see the use of the wildcard with both extends and super throughout
the collection types. Most often, you will see them used in method parameter types,
such as the addAll() method, which is defined for all Collections . Sometimes
you will see the collection types using the wildcard ( ? ) alone as a type parameter,
which is called an unbounded wildcard . The Collection removeAll() method
is such an example. In most cases, this usage is self-explanatory. You probably won't
be (probably shouldn't be) defining your own parameterized types using an unbounded
wildcard. If you try to do this, you will soon learn there isn't much you can do with it.
If you understand concrete parameterized types, wildcard parameterized types, and the
concept of bounded and unbouned types, as described in this recipe, you have most of
what you need to work with the generic collection types, and create your own generic
types if you so chose.
Now that we've talked a lot about parameterizing types, we're going to tell you to
forget about some of it. When Java 7 was released, a new feature called the diamond
(sometimes seen referred to as the diamond operator , although it is not considered to
Search WWH ::




Custom Search