Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to iterate on a hashmap of generics?
    text
    copied!<p>I have an object model which have a parent, that I'll call here MyParent.java. This class have two sub-classes named MySub1.java and MySub2.java.</p> <p>I have two HashMaps, one containing MySub1 instances and the other containing MySub2 instances. I'm trying to do a piece of code that can handle both HashMaps and do exactly the same thing (later on, having MySub1 or MySub2 instances will have some effect, but not here).</p> <p>Here is the part of code that does compile : </p> <pre><code>HashMap&lt;String, ? extends MyParent&gt; map = null; if (some condition) map = // get a HashMap&lt;String, MySub1&gt; if (some other condition) map = // get a HashMap&lt;String, MySub2&gt; </code></pre> <p>But now, I cannot figure out how to iterate on the <code>map</code> variable. I need to do it through an iterator and not though an iteration over the elements of the <code>keySet()</code> because I will need to remove some of the elements from the hashmap.</p> <p>Here is the part of my code that does NOT compile : </p> <pre><code>if(map != null &amp;&amp; map.size() &gt; 0){ Iterator&lt;Entry&lt;String, ? extends MyParent&gt;&gt; i = map.entrySet().iterator(); while(i.hasNext()){ Map.Entry&lt;String, MyParent&gt; pair = (Map.Entry&lt;String, MyParent&gt;) i.next(); // get the object from the pair and handle it } } </code></pre> <p>Eclipse does print me this error message on the line where I do create the iterator : </p> <pre><code> cannot convert from Iterator&lt;Map.Entry&lt;String,capture#5-of ? extends MyParent&gt;&gt; to Iterator&lt;Map.Entry&lt;String,? extends MyParent&gt;&gt; </code></pre> <p>I really dont get the error message. If I change the first line of my code for :</p> <pre><code>HashMap&lt;String, MyParent&gt; map = null </code></pre> <p>Now the code that was not working does work, but the working code does not work anymore with this error message : </p> <pre><code>cannot convert from HashMap&lt;String,MySub1&gt; to HashMap&lt;String,MyParent&gt; </code></pre> <p>Any idea ?</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