Is it possible to use a generic type list in Java?

I have the following general type:

public class Library<T> {}

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

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

Then I need to put this list on a general list. First I tried this:

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

The code above allowed me to add all the libraries to a flat list. However, this is not what I want. I want to have a list of typed libraries in another list. For example, index 0 is a list of video libraries, index 1 is a list of photo libraries, etc. I tried to do the following:

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

This does not work. When I tried to add to the list, he told 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?

+4
source share
3

, ArrayList<Library<?>> ArrayList<Library<Photo>. :

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

, Java-

+2

,

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

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

You must declare listTopLibraryhow

ArrayList<ArrayList<? extends Library<?>>> listTopLibrary
0
source

All Articles