Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is adding a subclass a of type in a collection is illegal?

given this code snippet

    //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 is that num.add(doub) will not be allowed? isn't List<List<Number>> a super type of List<List<Double>> ?

like image 703
KyelJmD Avatar asked Aug 30 '12 14:08

KyelJmD


1 Answers

Generics inheritance is little different than our understanding of inheritance. If you would like to use subclass types you need to define bounds (wildcards) using either extends (or) super in generics.

enter image description here

like image 61
kosa Avatar answered Oct 23 '22 09:10

kosa