Reputation: 1843
I saw the following recently on this site:
for (HashMap.Entry<Object,Object> e : new TreeMap<>().entrySet())
System.out.println(e);
To my surprise, this compiles and runs fine. I have also tried adding entries to the map so there is actually something to downcast and fail doing so, this worked fine as well. How can a TreeMap
entry be cast to HashMap.Entry
? These two aren't even on the same branch of the hierarchy.
Although this matter is resolved now, I include the following just for fascination—the following does not compile:
for (TreeMap.Entry<Object,Object> e : new HashMap<>().entrySet())
System.out.println(e);
It happens that TreeMap
defines TreeMap.Entry
, which hides Map.Entry
.
Upvotes: 5
Views: 85
Reputation: 279920
Although you are accessing it on HashMap
, Entry
is actually a (implicitly static
) member type declared in Map
. TreeMap#entrySet
has a return type of Set<Map.Entry<K,V>>
. This is the same Entry
type.
Upvotes: 9
Reputation: 15698
new TreeMap<>().entrySet() returns Set<Map.Entry<K,V>>
and you are iterating over every entry of the set (Entry<Object, Object>)
. Hence it compiles. In java 8 you can replace the for loop like
new TreeMap<>().entrySet().forEach(System.out::println);
Upvotes: 1