William F. Jameson
William F. Jameson

Reputation: 1843

Confusing type relationship

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.

Update

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

Answers (2)

Sotirios Delimanolis
Sotirios Delimanolis

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

sol4me
sol4me

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

Related Questions