tags:

views:

113

answers:

4

Why does this work:

List<?> list = new LinkedList<Integer>();

while this gives a type dismatch error:

List<List<?>> list = new LinkedList<List<Integer>>();

Why is this? Ist there a way around this, without using raw types?

+2  A: 

Try

List<? extends List<?>> list = new LinkedList<List<Integer>>();

Note: you should be aware that when you use a collection like List you will only be able to use it in "read only" mode (except for adding null values).

Zed
A: 

The way around this is

List<List<?>> list = new LinkedList<List<?>>();

You've not really lost anything there, either - your specification of Integer wasn't going to be helpful anywhere, since list defined the inner Lists as using ?

Jon Bright
A: 

Use,

List<?> list1 = new LinkedList<List<Integer>>();
adatapost
+2  A: 

To actually answer your question:

In the first case, "list" holds a list of one particular, unspecified type - in this case, Integer.

In the second case, "list" holds a list of lists, but each of the sublists may be of any particular type, but the following would be perfectly fine (note the types of the two lists being added):

List<List<?>> list = new LinkedList<List<?>>();
list.add(new LinkedList<Integer>());
list.add(new LinkedList<Double>());

It's very similar to the reason why you can't do

List<Object> listO = new List<Number>();

There are operations that would be perfectly valid on your list of lists of ? that would be illegal on the list of lists of Integers.

In order to do what you want (have a list of lists, where all the sublists are unique to a particular type), I think Zed's answer is about as close as you'll get.

Sbodd