List of a list of generic type in Java possible?

110 views Asked by At

I have the following generic type:

public class Library<T> {}

I need to put each generic type into a list - for example:

ArrayList<Library<Photo>> listPhotoLibrary
    = new ArrayList<Library<Photo>>();
ArrayList<Library<Video>> listVideoLibrary
    = new ArrayList<Library<Video>>();

I then need to put these list into a generic list. First I tried this:

ArrayList<Library<?>> listTopLibrary = new ArrayList<Library<?>>();

The above code allowed me to add all libraries into a flat list. However, this is not what I want. What I want is to have the list of typed libraries within another list. For example, index 0 is a list of Video libraries, index 1 is a list of Photo libraries and so on. I tried the below to accomplish this:

ArrayList<ArrayList<Library<?>>> listTopLibrary
    = new ArrayList<ArrayList<Library<?>>>();

This is not working. When I tried to add to the list, it is telling me:

The method add(ArrayList<Library<?>>) in the type ArrayList<ArrayList<Library<?>>>
is not applicable for the arguments (ArrayList<Library<Photo>>)

Any idea why the compiler is complaining? And if there is a way around this?

3

There are 3 answers

1
mkobit On BEST ANSWER

It is a compilation error because ArrayList<Library<?>> is not a supertype of ArrayList<Library<Photo>. You can declare the array like this:

ArrayList<ArrayList<? extends Library<?>>> listTopLibrary = new ArrayList<>();

A thorough explanation why can be found at Java nested generic type

0
Misha On

ArrayList<Library<?>> is not a supertype of ArrayList<Library<Photo>>

You have to declare listTopLibrary as

ArrayList<ArrayList<? extends Library<?>>> listTopLibrary
0
ashokramcse On

You can Fix this by using

List<ArrayList<? extends Library<?>>> listTopLibrary = new ArrayList<>();