<p>Why do I get compiler errors with this Java code?</p>

<pre><code>1  public List&lt;? extends Foo&gt; getFoos()
2  {
3    List&lt;? extends Foo&gt; foos = new ArrayList&lt;? extends Foo&gt;();
4    foos.add(new SubFoo());
5    return foos;
6  }</code></pre>

<p>Where 'SubFoo' is a concrete class that implements Foo, and Foo is an interface.</p>

<p>Errors I get with this code:</p>

<ul>
<li>On Line 3: "Cannot instantiate ArrayList&lt;? extends Foo&gt;"</li>
<li>On Line 4: "The method add(capture#1-of ? extends Foo) in the type List&lt;capture#1-of ? extends Foo&gt; is not applicable for the arguments (SubFoo)"</li>
</ul>

<p><b>Update:</b> Thanks to Jeff C, I can change Line 3 to say "new ArrayList&lt;Foo&gt;();".  But I'm still having the issue with Line 4.</p>

Use this instead:
```
```
1  public List<? extends Foo> getFoos()
2  {
3    List<Foo> foos = new ArrayList<Foo>(); /* Or List<SubFoo> */
4    foos.add(new SubFoo());
5    return foos;
6  }
```
```
Once you declare foos as
```
List<? extends Foo>
```
, the compiler doesn't know that it's safe to add a SubFoo. What if an
```
ArrayList<AltFoo>
```
had been assigned to
```
foos
```
? That would be a valid assignment, but adding a SubFoo would pollute the collection.