Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusing type relationship

Tags:

java

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.

like image 852
William F. Jameson Avatar asked Sep 16 '14 20:09

William F. Jameson


People also ask

What is a confusing relationship?

You feel as if you do not enjoy time togetherIf you dread time with your partner or feel that you do not have fun together, you may be in a confusing relationship. Time spent with someone you love should be enjoyable, and you shouldn't feel like you are trying to force yourself to have a good time.

What are the 4 types of relationships?

There are many different types of relationships. This section focuses on four types of relationships: Family relationships, Friendships, Acquaintanceships and Romantic relationships.

What is an example of a complicated relationship?

This a classic example of what a complicated relationship means. More reasons include that one of you is married and you are having an affair, you are working together, your friends or family don't approve or think this person is good for you, and the list goes on.


2 Answers

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.

like image 116
Sotirios Delimanolis Avatar answered Sep 23 '22 06:09

Sotirios Delimanolis


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);
like image 39
sol4me Avatar answered Sep 23 '22 06:09

sol4me