Is it possible to have a collection of shared collections?

I am writing code that should handle an arbitrary number of doubling lists. However, although I can declare functional parameters like List<List<Double>> , I cannot create the actual instances, since I need to create instances of a specific class, such as ArrayList

I tried

 List<? extends List<Double>> inputs = new ArrayList<List<Double>>(); inputs.add(new ArrayList<Double>()); 

and

 List<? extends List<? extends Double>> inputs = new ArrayList<List<Double>>(); inputs.add(new ArrayList<Double>()); 

but in both cases, I get a compilation error when add() called, saying that the method is not applicable for arguments like ArrayList<Double>

It works

 List<List<Double>> inputs = new ArrayList<List<Double>>(); inputs.add((List<Double>) new ArrayList<Double>()); 

but itโ€™s somehow ugly to use throws in this way. Is there a better approach?

+4
source share
3 answers

You can omit the cast, as this is absolutely true. Each ArrayList is a list.

 List<List<Double>> inputs = new ArrayList<List<Double>>(); inputs.add(new ArrayList<Double>()); 
+7
source

You do not understand what a wildcard means. <? extends List> <? extends List> does not mean "everything that extends the list", it means "Some specific thing that extends the list, but we donโ€™t know what it is." So it is illegal to add an ArrayList to this because we donโ€™t know if the ArrayList is specific to that in this collection.

Just old:

  List<List<Double>> list = new ArrayList<List<Double>>(); list.add(new ArrayList<Double>()); 

works great

+3
source

Two very different situations when defining a type of type must be declared:

1) in an open interface. use the correct abstract type.

  public List<List<Double>> querySomething(); 

2) as a implementation detail. use concrete type

  ArrayList<ArrayList<Double>> list = new ArrayList<ArrayList<Double>>(); 

I assume that you are in the second case.

0
source

All Articles