Reputation: 779
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?
Upvotes: 4
Views: 111
Reputation: 47319
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
Upvotes: 2
Reputation: 2861
You can Fix this by using
List<ArrayList<? extends Library<?>>> listTopLibrary = new ArrayList<>();
Upvotes: 1
Reputation: 28183
ArrayList<Library<?>>
is not a supertype of ArrayList<Library<Photo>>
You have to declare listTopLibrary
as
ArrayList<ArrayList<? extends Library<?>>> listTopLibrary
Upvotes: 0