Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The error you get in your first one is:</p> <pre><code>Type mismatch: cannot convert from element type Object to Map.Entry </code></pre> <p>This is because the compiler converts your FOR-IN loop:</p> <pre><code>for (Entry entry : anyMap.entrySet()) { } </code></pre> <p>To:</p> <pre><code>for (Iterator i = anyMap.entrySet().iterator(); i.hasNext();) { Entry e = i.next(); // not allowed } </code></pre> <p>Your second example works, <strong>but only through cheating!</strong> You are doing an unchecked cast to get <code>Set</code> <em>back</em> into a <code>Set&lt;Entry&gt;</code>.</p> <pre><code>Set&lt;Entry&gt; entries = anyMap.entrySet(); // you get a compiler warning here for (Entry entry : entries) { } </code></pre> <p>Becomes:</p> <pre><code>Set&lt;Entry&gt; entries = anyMap.entrySet(); for (Iterator&lt;Entry&gt; i = entries.iterator(); i.hasNext(); ) { Entry e = (Entry) i.next(); // allowed } </code></pre> <hr/> <p><strong>Update</strong></p> <p>As mentioned in comments, the type information is getting lost in both examples: because of the compiler's raw type erasure rules.</p> <p>To provide backwards compatibility, <strong>ALL</strong> methods of raw type instances are replaced by their <em>erased</em> counterparts. So, because your <code>Map</code> is a raw type, it all gets erased. Including its <code>Set&lt;Map.Entry&lt;K, V&gt;&gt; entrySet();</code> method: your raw type instance will be forced to use the erased version: <code>Set entrySet()</code>.</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