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?
It is a compilation error because
ArrayList<Library<?>>
is not a supertype ofArrayList<Library<Photo>
. You can declare the array like this:A thorough explanation why can be found at Java nested generic type