Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

2.2.8 小节对HashMap树化的描述有一点问题 #735

Open
XuyiK opened this issue Apr 18, 2020 · 1 comment
Open

2.2.8 小节对HashMap树化的描述有一点问题 #735

XuyiK opened this issue Apr 18, 2020 · 1 comment

Comments

@XuyiK
Copy link

@XuyiK XuyiK commented Apr 18, 2020

作者在 JDK1.8之后 这一小节的开头中写道:

JDK1.8之后再解决哈希冲突问题时有了较大的变化,当链表长度大于阈值(默认为8)时,将链表转化为红黑树,以减少搜索时间

这段话加粗部分的描述是不准确的,当链表长度大于阈值时,会尝试调用树化方法treeifyBin,但这不意味着会将链表转为树:

微信截图_20200418102018

当我们查看树化方法treeifyBin(JDK1.8 HashMap源码)时,应注意到这么一行代码(757行):

微信截图_20200418102319

我们发现,当哈希表的length小于MIN_TREEIFY_CAPACITY (默认为64)时,并不会真正树化,而只是执行resize(),也就是扩容的操作,这一点在对树化方法treeifyBin以及MIN_TREEIFY_CAPACITY
的注释中都有提到:

微信截图_20200418102713

微信截图_20200418102733

如果我的看法有什么错漏之处,恳请大家补充指正

@debugjoker
Copy link

@debugjoker debugjoker commented Apr 25, 2020

😊是的,你说的没错。当链表的长度超过了默认阈值8的时候并不是立马就树形化,在treeifyBin(Node<K,V>[] tab, int hash)方法里面还要判断下 table 的 length 是否大于64,小于64是直接resize的。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
2 participants
You can’t perform that action at this time.