• Post Reply Bookmark Topic Watch Topic
  • New Topic

Problem looping over iterator of Map with bounded type  RSS feed

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
Does anyone have any idea why in Java6 I get the following error:

incompatible types
required: java.util.Iterator<java.util.Map.Entry<? extends java.lang.Number, java.lang.String>>
found: java.util.Iterator<java.util.Map.Entry<capture#19 of ? extends java.lang.Number, java.lang.String>>

when trying to compile this:

while the following compiles fine?


Thanks,
Edward

 
Greenhorn
Posts: 16
Eclipse IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

returns actual passed type.

For example, if you call test1() with param new HashMap<Integer, String>() it means that stuff.entrySet().iterator() returns Iterator<Entry<Integer, String>>.
But in general Iterator<Entry<Integer, String>> not compatible with Iterator<Entry<? extends Number, String>>
 
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
... and welcome to the Ranch
 
Saloon Keeper
Posts: 7993
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Okay, this is going to be *really* difficult to explain, but here's my best shot.

stuff.entrySet().iterator() returns an Iterator<T>, where T is the concrete type (or capture) of the entry set.

Your variable expects an Iterator<X>. So X and T need to be *exactly* the same type.

Here, X is Entry<? extends Number, String>, and T is Entry<SomeNumber, String>. This is *not* exactly the same type.

So, your variable should not be an Iterator<X>, but Iterator<? extends T>.

The final solution is:
 
Stephan van Hulst
Saloon Keeper
Posts: 7993
143
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Easier would probably be to do the capture ahead of time, so your variable is sure to match up:
 
Edward Ross
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell thanks for the welcome.
Stephan and Mykhailo, thank you, thank you, thank you. That really explains it.

Edward
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!