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 · 3 comments
Open

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

XuyiK opened this issue Apr 18, 2020 · 3 comments
Labels
bug Content error discuss discuss a problem enhancement New feature or request or suggestion perfect Improve knowledge points or descriptions

Comments

@XuyiK
Copy link

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
Contributor

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

@shahainloong
Copy link
Contributor

我也觉得是这样的,小于64是resize扩容,至少大于等于64才会去做链转树操作。

@Snailclimb
Copy link
Owner

作者在 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

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

非常👍 简单修改完善了一下:
image

@Snailclimb Snailclimb added bug Content error discuss discuss a problem enhancement New feature or request or suggestion perfect Improve knowledge points or descriptions labels Feb 25, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Content error discuss discuss a problem enhancement New feature or request or suggestion perfect Improve knowledge points or descriptions
Projects
None yet
Development

No branches or pull requests

4 participants