开发者

Is is possible to have a collection of generic collections?

开发者 https://www.devze.com 2023-03-10 14:03 出处:网络
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 tro开发者_J

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 tro开发者_JAVA百科uble 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?


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>());


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


Two very different situations when deciding what kind of type should be declared:

1) in a public interface. use proper abstract type.

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

2) as an implementation detail. use concrete type

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

I'm guessing you are on the 2nd case.

0

精彩评论

暂无评论...
验证码 换一张
取 消