0

Questions asked inline within codes.

class A1{}
class B1 extends A1{}
class C1 {}

public class X {

    public void meth(List<? super B1> l){
        l.add(new A1());//why this is not a valid syntax,why we can only add new B1() ?
    }

    public void meth2(List<? extends A1> l){
        //and here, why can't we add anything ?
    }
}
Dijkgraaf
  • 10,108
  • 17
  • 36
  • 52
pinaki
  • 321
  • 2
  • 3
  • 14

1 Answers1

0

The point of List<? ... > is that you don't know what type the list is supposed to contain.

You can't add a B1 to a List<? super B1>, because it might actually be a List<B1>, which cannot contain an A1.

You can't add anything (other than null) to a List<? extends A1> because you don't know anything about what type it's supposed to contain. It might be a List<some class that inherits B1>.

SLaks
  • 837,282
  • 173
  • 1,862
  • 1,933