Search code examples
javagenericswildcardpecs

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>> ?


Solution

  • 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