title: Compiler error on Java generic interface with a List<> method
body: <p>I don't understand the compiler error resulting from the following code. I define a generic interface, see Task, with two methods: <code>U doSomething(String value)</code> and <code>List&lt;Integer&gt; getIDs()</code>. The doSomething() method actually uses the generic type as the type of its return value, but doesn't seem to be causing problems. The <code>getIDs()</code> method returns a List, which is unrelated to the type of Task, but it is causing problems when using for..each statement to iterate over the return value. The following compiler error occurs.</p>
  
  <blockquote>
  <pre><code>error: incompatible types
      for (Integer value : task.getIDs()){
  required: Integer
  found:    Object
  </code></pre>
  </blockquote>
  
  <p>It seems that the type erasure on the interface is causing the compiler to forget the declared type on the second method, which is unrelated to the generic type. <strong>Or in other words why is the generic type on the interface affecting how the compiler understands the return value on the <code>getIDs()</code> method and specifically in the context of a for..each statement?</strong></p>
  
  <p>Apparently if I get reference to the list outside of the for..each there is no problem, but not directly.</p>
  
  <pre class="lang-java prettyprint-override"><code>public class InterfaceTest {
     public static void main(String[] args) {
        Task task = new MyTask();
        // no complaints about the type here     
        List&lt;Integer&gt; values = task.getIDs();
  
        // getting a compiler error for this line
        for (Integer value : task.getIDs()){
  
        }
     }
  }
  
  
  interface Task&lt;U&gt;{
     U doSomething(String value);
     List&lt;Integer&gt; getIDs();
  }
  </code></pre>
  
  <hr>
  
  <p>The implementation of the interface isn't necessary to demonstrate the point, but I didn't want to leave the reference <code>Task task = null;</code> and have answer's telling me that's the problem.</p>
  
  <pre class="lang-java prettyprint-override"><code>class MyTask implements Task&lt;Boolean&gt;{
  
     @Override
     public Boolean doSomething(String value) {
        System.out.println(value);
        return false;
     }
  
     @Override
     public List&lt;Integer&gt; getIDs() {
        return Arrays.asList( 1, 2, 3, 4 );
     }
  }
  </code></pre>