MyClass e = new MyClass();
List<Object> ok = new ArrayList<Object>();
List<? extends Object> ko = new ArrayList<Object>();
ok.add(e);
ko.add(e); // doesn't compile
Why does it doesn’t compile? MyClass is whatever a subclass of Object…
For information, I get the following message:
The method add(capture#1-of ? extends Object) in the type List<capture#1-of ? extends Object> is not applicable for the arguments (MyClass)
This is your problem:
That means “it’s a list of some type T which extends Object, but I don’t care what T is”.
So this would be valid:
… but you wouldn’t want:
to compile at that point, would you? Because a
MyClassisn’t aBanana.See the Java generics FAQ for much more information.