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

HashMap源码分析中put的方法的流程图的疑问 #608

Closed
zhongshanhao opened this issue Dec 31, 2019 · 7 comments
Closed

HashMap源码分析中put的方法的流程图的疑问 #608

zhongshanhao opened this issue Dec 31, 2019 · 7 comments
Labels
bug Content error enhancement New feature or request or suggestion

Comments

@zhongshanhao
Copy link

图中若key存在,直接覆盖其节点值,这时不应该将size加1吧?按照源码分析应该直接返回被覆盖之前的值吧?
@LiWenGu
Copy link
Contributor

LiWenGu commented Dec 31, 2019

直接覆盖之后应该就会 return,不会有后续操作。这个图确实有问题。
参考 JDK8 HashMap.java 658 行

@zhongshanhao
Copy link
Author

直接覆盖之后应该就会 return,不会有后续操作。这个图确实有问题。
参考 JDK8 HashMap.java 658 行

确实,源码实现是直接返回被覆盖的值的。

@Snailclimb Snailclimb added bug Content error enhancement New feature or request or suggestion labels Jan 22, 2020
@softwareCQT
Copy link

如果是putIfAbsent的话才不会被覆盖掉,返回原来的值,主要看那个onlyIfAbsent

@hokage123
Copy link

PutIfAbsent Or OnlyIfabsent serve what purpose
If Put() method work for the key if it is not present
Otherwise it overrides the value of key.

@shahainloong
Copy link
Contributor

扩容之后返回null,直接覆盖的话会返回原来的value值。

@llnancy
Copy link

llnancy commented Nov 16, 2020

长度大于8后转换成红黑树那里有问题吧?后续不会执行红黑树插入逻辑,只是长度大于8后会进行树化,节点已经在上一步插入至链表了。

参考 JDK8 HashMap.java 642 行 -> 执行尾插至链表逻辑
参考 JDK8 HashMap.java 644 行 -> 判断大于8后执行treeifyBin树化逻辑

@sAMs126
Copy link

sAMs126 commented Mar 17, 2021

有一个疑问,是否可以这样理解,除了直接追加数组元素 tab[i] = newNode(hash, key, value, null); 这种方式,其他的插入/覆盖方式,都不会对整个数组的长度产生影响,也就无从谈起数组扩容

但是 treeifyBin(tab, hash); 方法中的

if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY) resize();

难道是仅仅只会在整个数组为空,或者长度小于 64 是进行扩容?

Replaces all linked nodes in bin at index for given hash unless table is too small, in which case resizes instead.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Content error enhancement New feature or request or suggestion
Projects
None yet
Development

No branches or pull requests

8 participants