Forums Register Login

generics, Map.entrySet() and casting

+Pie Number of slices to send: Send
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?

+Pie Number of slices to send: Send
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();

to

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.
Space seems cool in the movies, but once you get out there, it is super boring. Now for a fascinating tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 5324 times.
Similar Threads
generics
generics - incompatible types
Generics -really very hard question
Compiler error in case of advanced for-each loop of Map.Entry
Why are Generics necessary here?
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 09:15:36.