Why does Java not allow nested generics to be injected?

If I write:

List<List<String>> strings = new ArrayList<ArrayList<String>>(); 

I get the following compiler error:

 Type mismatch: cannot convert from ArrayList<ArrayList<String>> to List<List<String>> 

Why?

+4
source share
4 answers

Generics are not co-options, so you have to use:

 List<List<String>> strings = new ArrayList<List<String>>(); 

Notice how the outer right declaration of an ArrayList can "become" a List . The same cannot be applied to everything that appears in generics.

+8
source

You can make the necessary code, you just need to update your initialization:

 List<List<String>> strings = new ArrayList<List<String>>(); 

Then for each item you want to add to the external list:

 strings.add(new ArrayList<String>()); 
+1
source

If it was allowed, you could end up relying on a list, which is an ArrayList at some point, and somewhere else.

For example, this would also be legal for this:

 ArrayList<ArrayList<String>> arrayLists = new ArrayList<ArrayList<String>>(); List<List<String>> unknownLists = arrayLists ; unknownLists.append(new LinkedList<String>()); for (ArrayList<String> l : arrayLists ) // (1) System.out.println(l); 

This will compile fine, but you will get a ClassCastException in (1).

0
source

You cannot do this because the type is persistent. However, you can write like this:

 List<? extends List<String>> strings = new ArrayList<ArrayList<String>>(); 
0
source

All Articles