I am trying to understand how these data structures actually are visualized. It is said that TreeMap
puts the entries in natural order [of keys] and LinkedHashMap
puts entries in the order in which they are inserted.
My question is, does the iteration over each of these data structures mean traversing over all the elements spread over all the buckets (or inner array)?
My understanding was that, for instance, in case of TreeMap
, elements with an identical hashcode are placed in a Tree structure [of some sort]. Therefore, if a TreeMap
has elements in 6 out of 16 indexes [in its bucket array], it would contain 6 Tree
's -- one for each.
Similarly, in case of LinkedHashMap
(which should have been called DoublyLinkedHashMap in reality), each bucket would have a doubly linked list of its own.
So, how does iteration actually take place? Does it happen over all the elements in all the buckets or only over elements of a single bucket? Am I wrong in my assumption?
P.S. And it seems like in Java 8, HashMap
implementation uses a Tree
or LinkedList
depending on the number of elements for each bucket containing more than 8 or less than 6 elements, respectively!
The source code for the normal implementations is in the src.zip file that comes with the Oracle JDK installs.
TreeMap
: As indicated in its documentation, it is a Red-Black tree. The critical code for simple forwards iteration over the keys is the methodstatic <K,V> TreeMap.Entry<K,V> successor(Entry<K,V> t)
. It recursively scans the tree, in the order left-parent-right. It depends for ordering on nodes being inserted in the tree according to their key order.LinkedHashMap
: It has a doubly linked list in arrival order imposed on top of a hash structure with buckets. The nested classEntry
extendsHashMap.Node
to addbefore
andafter
references. Normal forwards iteration follows theafter
chain.