From java 8
onwords, there is a performance improvement for HashMap
objects where there are lots of collisions in the keys by using balanced trees rather than linked lists to store map entries. The principal idea is that once the number of items in a hash bucket grows beyond a certain threshold, that bucket will switch from using a linked list of entries to a balanced tree. In the case of high hash collisions, this will improve worst-case performance from O(n)
to O(log n).
Basically when a bucket becomes too big (currently: TREEIFY_THRESHOLD = 8
), HashMap
dynamically replaces it with an ad-hoc implementation of tree map. This way rather than having pessimistic O(n)
we get much better O(log n)
.
Bins (elements or nodes) of TreeNodes
may be traversed and used like any others, but additionally support faster lookup when overpopulated. However, since the vast majority of bins in normal use are not overpopulated, checking for existence of tree bins may be delayed in the course of table methods.
Tree
bins (i.e., bins whose elements are all TreeNodes
) are ordered primarily by hashCode, but in the case of ties, if two elements are of the same “class C implements Comparable<C>
“, type then their compareTo()
method is used for ordering.
Because TreeNodes
are about twice the size of regular nodes, we use them only when bins contain enough nodes. And when they become too small (due to removal or resizing) they are converted back to plain bins (currently: UNTREEIFY_THRESHOLD = 6
). In usages with well-distributed user hashCodes
, tree bins are rarely used.
Link to java doc
Collection framework enhancements