Why do I get compiler errors with this Java code?
1 public List<? extends Foo> getFoos() 2 { 3 List<? extends Foo> foos = new ArrayList<? extends Foo>(); 4 foos.add(new SubFoo()); 5 return foos; 6 }
Where ‘SubFoo’ is a concrete class that implements Foo, and Foo is an interface.
Errors I get with this code:
- On Line 3: ‘Cannot instantiate ArrayList<? extends Foo>’
- On Line 4: ‘The method add(capture#1-of ? extends Foo) in the type List<capture#1-of ? extends Foo> is not applicable for the arguments (SubFoo)’
Update: Thanks to Jeff C, I can change Line 3 to say ‘new ArrayList<Foo>();’. But I’m still having the issue with Line 4.
Use this instead:
Once you declare foos as
List<? extends Foo>, the compiler doesn’t know that it’s safe to add a SubFoo. What if anArrayList<AltFoo>had been assigned tofoos? That would be a valid assignment, but adding a SubFoo would pollute the collection.