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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With