Why is adding a subclass of type a to the collection is illegal?

given this piece of code

    //Creates a list of List numbers
    List<List<Number>> num = new ArrayList<List<Number>>();
    //Creates a list of List doubles
    List<List<Double>> doub = new ArrayList<List<Double>>();
    //List of doubles
    List<Double> d = new ArrayList<Double>();
    d.add(2.5);
    d.add(2.6);
    doub.add(d);

    num.add(d);//This code will not compile

Why won't this num.add (doub) be resolved? not a List<List<Number>>supertype List<List<Double>>?

+5
source share
4 answers

Inheritance generics is slightly different from our understanding of inheritance. If you want to use subclass types, you need to define wildcards using either extends (or) super in generics.

enter image description here

+6
source

You are trying to add a list of lists to a list that accepts a list. (not after the edit I see)

Or maybe a little more confusing:

Your num list can only add List<Number>, you are trying to add a List<List<Double>>.

, , , .

num :

    List<List<? extends Number>> num = new ArrayList<List<? extends Number>>();

:

    num.add(d);

:

    num.add(doub);
+1

List<Double> List<Number>, List<>.

, List<List<Double>> List<List<Number>>, Java Generics. extends, .

0

, doub.add(d) num.add(doub) add(). doub.add(d) , num.add(doub).

,

num.add(d)

num.add(doub)

?

0
source

All Articles