Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is is possible to have a collection of generic collections?

Tags:

java

I'm writing some code that needs to process an arbitrary number of lists of doubles. However, although I can declare function parameters of type List<List<Double>> I'm having trouble creating actual instances since I need to create instances of a concrete class such as ArrayList

I've 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 compile error on the call to add() saying that the method is not applicable for arguments of type ArrayList<Double>

This works

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

but it's kind of ugly to have to use casts in this way. Is there a better approach?

like image 849
dsnowdon Avatar asked Dec 28 '22 19:12

dsnowdon


2 Answers

You can omit the cast since this one is perfectly valid. Each ArrayList is a List.

List<List<Double>> inputs = new ArrayList<List<Double>>();
inputs.add(new ArrayList<Double>());
like image 125
Sebastian Zarnekow Avatar answered Dec 30 '22 09:12

Sebastian Zarnekow


You're misunderstanding what the wildcard means. <? extends List> does not mean "anything that extends list" it means "Some specific thing that extends list, but we don't know what it is." So it's illegal to add an ArrayList to that, because we don't know if ArrayList is the specific thing that's in this collection.

Just plain old :

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

works fine

like image 45
Affe Avatar answered Dec 30 '22 10:12

Affe