为什么Java hashmap在数量为8的树上对bin进行树化,而在数量为6的树上进行非树化?

时间:2019-05-29 02:50:48

标签: java hashmap

请赐教。我只能想象这种情况可以避免在bin的计数为8时频繁地进行树化和取消树化。

/**
 * The bin count threshold for using a tree rather than list for a
 * bin.  Bins are converted to trees when adding an element to a
 * bin with at least this many nodes. The value must be greater
 * than 2 and should be at least 8 to mesh with assumptions in
 * tree removal about conversion back to plain bins upon
 * shrinkage.
 */
static final int TREEIFY_THRESHOLD = 8;

/**
 * The bin count threshold for untreeifying a (split) bin during a
 * resize operation. Should be less than TREEIFY_THRESHOLD, and at
 * most 6 to mesh with shrinkage detection under removal.
 */
static final int UNTREEIFY_THRESHOLD = 6;

实际上,我在问为什么值不相同。您能告诉我有关它们使用不同计数的原因的具体静态信息吗?

1 个答案:

答案 0 :(得分:1)

Hashmap是哈希表数据结构的实现。当我们使用哈希函数系统插入键值对时,将识别键的哈希值并将其插入相应的bin中。如果插入另一个键,则第二个键的值对和哈希值也将提供相同的值,它将进入相同的容器。这种情况称为哈希冲突。如果bin的大小很小,则稍后搜索元素时,bin的List / array实现会提供更好的性能。否则,bin大小很大,二叉树可能有助于轻松识别密钥。您注意到的是哈希表的性能优化。