Complex relationship type

I recently saw the following on this site:

for (HashMap.Entry<Object,Object> e : new TreeMap<>().entrySet()) System.out.println(e); 

To my surprise, this compiles and works just fine. I also tried adding entries to the card so that there really was something to knock down and not do it, this worked fine too. How to write TreeMap in HashMap.Entry ? These two are not even in the same hierarchy branch.

Update

Although this question is now resolved, I am including the following for hobby only: mdash: 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 .

+5
source share
2 answers

Although you access it on a HashMap , Entry is actually a (implicit static ) member type declared in Map . TreeMap#entrySet has a return type of Set<Map.Entry<K,V>> . This is the same type of Entry .

+9
source

new TreeMap<>().entrySet() returns Set<Map.Entry<K,V>> , and you repeat each record in the set (Entry<Object, Object>) . Therefore, it compiles. In java 8 you can replace the for loop like

 new TreeMap<>().entrySet().forEach(System.out::println); 
+1
source

Source: https://habr.com/ru/post/1202712/


All Articles