Note that there are some explanatory texts on larger screens.

plurals
  1. PORaw types with generic methods independent of the generic type
    text
    copied!<p>This a follow-up to <a href="https://stackoverflow.com/users/1658772/chrert">chrert</a>'s question <a href="https://stackoverflow.com/questions/16654561/generic-classes-with-collection-getter-of-other-types/16654735">Generic classes with Collection getter of other types</a>. If you can come up with a better title to my question, feel free to edit it:</p> <p>Following code contains a generic class <code>GenericClass&lt;T&gt;</code> with a method of return type <code>T</code> and another method with return type <code>Collection&lt;String&gt;</code>, which is obviously independent of <code>T</code>. </p> <p>Now, if I instantiate a raw <code>GenericClass</code> (which I would never do, so this question is more a theoretical question, to help understand what's going on) then calling that method in an enhanced for loop won't work, because all generic type information seem to get lost when using raw types. But then, when calling that same method in an assignment, it works (it warns about type unsafety, but it compiles).</p> <p>In my point of view, either both shouldn't work, or both should work. I don't understand why one works, and the other doesn't. Do you have any hints, or know any parts of the JLS that explain this behavior?</p> <pre><code>public class GenericClass&lt;T&gt; { T doSomething() { return null; } Collection&lt;String&gt; getCollection() { return Collections.emptyList(); } public static void main(String[] args) { GenericClass raw = new GenericClass(); // This will not compile (Error message below) for (String str : raw.getCollection()) { // Type mismatch: cannot convert from element type Object to String } // This is only a warning: // Type safety: The expression of type Collection needs unchecked conversion to conform to Collection&lt;String&gt; Collection&lt;String&gt; coll = raw.getCollection(); for (String string : coll) { // works just fine } } } </code></pre> <hr> <p>There is a related question, which, together with the accepted answer here, explains what's going on pretty good: <a href="https://stackoverflow.com/questions/662191/why-wont-this-generic-java-code-compile">Why won't this generic java code compile?</a></p>
 

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