Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy does the Java Compiler complain on using foreach with a raw type?
    primarykey
    data
    text
    <p>I got a strange compiler error when using generics within a for-each loop in Java. Is this a Java compiler bug, or am I really missing something here?</p> <p>Here is my whole class:</p> <pre><code>public class Generics&lt;T extends Object&gt; { public Generics(T myObject){ // I didn't really need myObject } public List&lt;String&gt; getList(){ List&lt;String&gt; list = new ArrayList&lt;String&gt;(); list.add("w00t StackOverflow"); return list; } public static void main(String...a){ Generics generics = new Generics(new Object()); for(String s : generics.getList()){ System.out.println(s); } } } </code></pre> <p>The compiler is complaining about the line with the for-each: "Type mismatch cannot convert from element type Object to String."<br> If I make this subtle change, it compiles:</p> <pre><code>public static void main(String...a){ Generics&lt;?&gt; generics = new Generics(new Object()); for(String s : generics.getList()){ System.out.println(s); } } </code></pre> <p>I know <code>getList()</code> does use generics, but it uses them in what I thought was a completely unrelated way. I could understand this if I were trying to iterate over something of type T and <code>getList()</code> returned a <code>List&lt;T&gt;</code> or something, but that's not the case here. The return type of <code>getList()</code> should have absolutely nothing to do with T and shouldn't care whether I use the raw type for my Generics object or not...right? Shouldn't these be completely unrelated, or am I really missing something here?</p> <p>Note that the code also compiles if I do this, which I thought should have been equivalent to the first as well:</p> <pre><code>public static void main(String...a){ Generics generics = new Generics(new Object()); List&lt;String&gt; list = generics.getList(); for(String s : list){ System.out.println(s); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload