Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Iterator implement in TreeSet

I read java source about TreeSet , but I can not find the implement of Iterator in TreeSet. Could anybody tell me how Iterator implements in TreeSet, and where is the source code in TreeSet? thanks!

like image 962
Zhong Yang Avatar asked Dec 04 '25 22:12

Zhong Yang


1 Answers

Well, if you look at the source code of TreeSet<E>.iterator() you see:

public Iterator<E> iterator() {
    return m.navigableKeySet().iterator();
}

Next search for the definition of m:

private transient NavigableMap<E,Object> m;

So obviously TreeSet points to a NavigableMap which is not really a surprise because TreeSet's JavaDoc says:

A NavigableSet implementation based on a TreeMap.

Okay, so let us check the source code of TreeMap. There you will find the method navigableKeySet() which was referenced above, pointing to a member named navigableKeySet which is of type TreeMap.KeySet<K>, a static inner class. There in turn you will find an iterator() method and so forth. The TreeMap class contains quite a lot of inner classes, the whole structure is pretty complex, but if you are interested you can sort it out by yourself. I think I gave you a good headstart. ;-)

like image 166
kriegaex Avatar answered Dec 06 '25 14:12

kriegaex