Java – iterator of wildcard type variables with upper bound
Hello, I'm trying to extend HashMap < string, string > to enforce the "all lowercase" rule
public class HttpQueryMap extends HashMap<String,String> { ... @Override public void putAll(Map<? extends String,? extends String> m) { ... Iterator<Map.Entry<String,String>> iterator = m.entrySet().iterator(); ... } ... }
I received a compile time error
incompatible types required: Iterator<Entry<String,String>> found: Iterator<Entry<CAP#1,CAP#2>> where CAP#1,CAP#2 are fresh type-variables: CAP#1 extends String from capture of ? extends String CAP#2 extends String from capture of ? extends String
The next solution can do this, but it's actually ugly:
public class HttpQueryMap extends HashMap<String,? extends String> m) { ... Map<String,String> m_str=new HashMap<String,String>(); m_str.putAll(m); Iterator<Map.Entry<String,String>> iterator = m_str.entrySet().iterator(); ... } ... }
As far as I know, the problem is the type variable string < map used in iterator Entry < string, string > > do not extend map meters
Solution
No iterators
The easiest way is to use a for - each loop Even in this case, you need to parameterize the entry with the same wildcards as in the given mapping The reason is entry is not a subtype of entry < string, string > The fact that string is the final class is irrelevant here because the compiler does not know this
for (Entry<? extends String,? extends String> entry : m.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); }
With iterator
If you really need an iterator, the compilation syntax is a little confusing:
Iterator<? extends Entry<? extends String,? extends String>> iterator = m.entrySet().iterator(); while (iterator.hasNext()) { Entry<? extends String,? extends String> entry = iterator.next(); String key = entry.getKey(); String value = entry.getValue(); }
I initially expected the iterator to be just iterator type < entry >, which initially looks like set < entry > this in turn seems to be in map .
But it's a little more complicated than that Here I found a possible answer:
http://mail-archives.apache.org/mod_mbox/harmony-dev/200605.mbox/%3Cbb4674270605110156r4727e563of9ce24cdcb41a0c8 @mail. gmail. com%3E
What's interesting is this: