This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
The moose likes Java in General and the fly likes generics, Map.entrySet() and casting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "generics, Map.entrySet() and casting" Watch "generics, Map.entrySet() and casting" New topic

generics, Map.entrySet() and casting

ayco holleman

Joined: Feb 04, 2003
Posts: 4
I do not understand why the following code (and any plausible variation on it) refuses to compile

if (bean instanceof Map<?, ?>) {
Map<?,?> map = ((Map<?,?>) bean); // works
Set<Map.Entry<?, ?>> set = map.entrySet(); // error
// ...

Type mismatch: cannot convert from Set<Map.Entry<capture#4-of ?,capture#5-of ?>> to Set<Map.Entry<?,?>>

Only when I use the following sledge hammer (just short of doing completely away with generics), do I get the code to compile:

if (bean instanceof Map<?, ?>) {
Map<?,?> map = ((Map<?,?>) bean); // works
Set<?> set = map.entrySet(); // works
// ...

But then, of course, I cannot assume that my set consists of Map.Entry elements. I have tried variations using "<? extends Object" or simply "<Object", but it all refuses to compile.

So what syntax should I use to give my code a cool generic glow?

O Wright

Joined: Apr 23, 2007
Posts: 3
I know this is a late reply but I saw this looking for an answer as well.....

You can change

Set<Map.Entry<?, ?>> set = map.entrySet();


Set< ? extends Map.Entry<?,?>> set = map.entrySet();

and it will compile.

I'm not too impressed with java's generics because it seems that this can be assumed that the generic type can include the generic type's subtypes.

SCJA : 94% : 4/20/2007<br /> <br />There are 10 types of people in this world, those who understand binary and those who don't.
I agree. Here's the link:
subject: generics, Map.entrySet() and casting
It's not a secret anymore!