为什么HashMap链表长度超过8会转成红黑树结构

JDK1.8后的HashMap在链表长度超过8时会转换为红黑树,以提升搜索效率。这是因为红黑树的插入、删除和查找操作的时间复杂度为log(n),相较于链表更优。此外,由于链表长度超过8的概率较低,这种转换能有效平衡空间和性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

底层数据结构: JDK1.8 以后的 HashMap 在解决哈希冲突时有了较大的变化,当链表长度大于阈值(默认为8)时,将链表转化为红黑树,以减少搜索时间。
为什么HashMap链表长度超过8会转成红黑树结构

红黑树的插入、删除和遍历的最坏时间复杂度都是log(n),

log(6)=2.6

链表 8/2=4

红黑树 log(8)=3

2.由频率表可以看出,桶的长度超过8的概率非常非常小。 阈值为8。

Because TreeNodes are about twice the size of regular nodes, we use them only when bins contain enough nodes to warrant use (see TREEIFY_THRESHOLD). And when they become too small (due to removal or resizing) they are converted back to plain bins. In usages with well-distributed user hashCodes, tree bins are rarely used. Ideally, under random hashCodes, the frequency of nodes in bins follows a Poisson distribution (http://en.wikipedia.org/wiki/Poisson_distribution) with a parameter of about 0.5 on average for the default resizing threshold of 0.75, although with a large variance because of resizing granula

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值