Search code examples
javalistgenericscollectionsgeneric-collections

Specific generic type of lists within a list


I have a list of lists.

I would like to know how I can restrict the generic types of each of the inner lists so each element of the outer list contains an inner list that can only contain one type of object. So far I have tried this:

List<ArrayList<?>> l = new ArrayList<ArrayList<?>>();

But there are ways to add types of objects to the inner lists which do not belong. Is there a way to specify the type the inner list accepts?

For example, if I have the following inner lists,

ArrayList<T1> innerList = new ArrayList<T1>();
ArrayList<T2> innerList2 = new ArrayList<T2>();
ArrayList<T3> innerList3 = new ArrayList<T3>();

How would I create an outer list which can contain all of the inner lists while retaining the specific type that the inner list contains.

Also I am not sure if this is possible, or if what I am doing is bad design. If it is bad design, insight onto a better design (maybe there is a different collection that does this better) would be very appreciated.


Solution

  • If the types of the inner lists have nothing in common, there is no way to narrow it down, and the wildcard ? is the best you can do.

    If T1 T2 and T3 all extend from a base class B, then you can write:

    List<List<? extends B>> outerList = new ArrayList<List<? extends B>>();
    

    Or likewise if they share an interface. It depends on what common functionality they are implementing that requires them to be stored in the same list.

    If you want help with the design you will need to explain your situation with an example/use case. It's probably not good design to keep them in the same collection if they have nothing in common.