java - Return type of generic Map.entrySet() -


map.entryset() declared as:

set<map.entry<k, v>> entryset(); 

somewhere define variable this:

map<? extends number, string> wildcardmap = new hashmap<>(); 

now, assume type param k ? extends number , this:

set<map.entry<? extends number, string>> entries = wildcardmap.entryset(); 

but gives compilation error, , have write:

set<? extends map.entry<? extends number, string>> entries = wildcardmap.entryset(); 

can explain why wildcard necessary right before map.entry?

the wildcard ? extends number means specific (unknown us) type extends number. let's try 1 possible type be, integer, , see happens:

map<integer, string> wildcardmap;  // doesn't compile set<map.entry<? extends number, string>> entries = wildcardmap.entryset(); 

why? because wildcardmap.entryset() returns set<map.entry<integer, string>>, not subtype of set<map.entry<? extends number, string>>.

generics invariant , type arguments must match exactly, unless type argument wildcard. wildcard @ deeper level doesn't count (it's part of type). set<map.entry<integer, string>> not subtype of set<map.entry<? extends number, string>>, though map.entry<integer, string> subtype of map.entry<? extends number, string>, how list<string> not subtype of list<object> though string subtype of object.


Comments

Popular posts from this blog

Django REST Framework perform_create: You cannot call `.save()` after accessing `serializer.data` -

Why does Go error when trying to marshal this JSON? -