Omitting <?> unintuitively breaks this code : <p>I have created a MWE where changing a single line by adding <code>&lt;?&gt;</code> solves a compiler error.</p>

<p>The following code does not compile:</p>

<pre><code>import java.util.List;

public class MainClass {

    public void traverse() {
        List&lt;MyEntity&gt; list = null /* ... */;
        for (MyEntity myEntity : list) {
            for (String label : myEntity.getLabels()) { // &lt;-- Offending Line
                /* ... */
            }
        }
    }

    interface MyEntity&lt;T&gt; {
        T get();

        List&lt;String&gt; getLabels();
    }
}
</code></pre>

<p>The compiler error is:</p>

<pre><code>Error:(9, 51) java: incompatible types: java.lang.Object cannot be converted to java.lang.String
</code></pre>

<p>Changing the definition in the offending line from <code>MyEntity myEntity</code> to <code>MyEntity&lt;?&gt; myEntity</code> solves the issue. I wonder why is the return type of this for-each treated as an <code>Object</code> and not as a <code>String</code>, unless I add the wildcard to the parent class? Note that <code>getLabels()</code> itself does not contain generics.</p>

<p>According to <a href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.14.2">Chapter 14.14.2. of the Java Language Specification</a>, a for-each is compiled to a loop using an iterator. Interestingly, expanding the for-each to such an iterator manually <strong>works</strong>:</p>

<pre><code>Iterator&lt;String&gt; iterator = myEntity.getLabels().iterator();
while (iterator.hasNext()) {
    String label = iterator.next();
    /* ... */
}
</code></pre>

<p>Can anyone explain why?</p>
