gpt4 book ai didi

java - 当桶中的条目对象从阈值减少后,JDK 8中的hashmap是否会再次调整自身大小?

转载 作者:行者123 更新时间:2023-12-01 16:52:09 25 4
gpt4 key购买 nike

我发现一个博客,其中给出了 JDK8 中 hashmap 的更改和性能改进。

From JDK 1.8 onwards HashMap has introduced an improved strategy to deal with high collision rate. Since a poor hash function e.g. which always return location of same bucket, can turn a HashMap into linked list, i.e. converting get() method to perform in O(n) instead of O(1) and someone can take advantage of this fact, Java now internally replace linked list to a binary true once certain threshold is breached. This ensures performance or order O(log(n)) even in the worst case where a hash function is not distributing keys properly.

在 JDK 8 中,我们都知道,每当达到阈值时,链表就会将自身大小调整为二叉树。我想知道当节点数量小于阈值时,二叉树是否会再次将自身大小重新调整为链表。?

在一次采访中有人问我这个问题,我说不,因为每次数字发生变化时它都不会不断调整自己的大小。我说得对吗?

引用博客:

  1. http://javarevisited.blogspot.com/2014/07/java-optimization-empty-arraylist-and-Hashmap-cost-less-memory-jdk-17040-update.html
  2. http://javarevisited.blogspot.com/2011/02/how-hashmap-works-in-java.html

最佳答案

这是 HashMap 源中注释的一部分:

 * 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.

再往下看,我看到了这个:

/**
* 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;

所以这个问题的答案是“是和否”。当大小低于相同阈值时,它不会自行调整大小,但当大小低于不同阈值时,它会调整大小。

我不明白为什么你会在面试中被问到这个问题——你所申请的公司真的希望你记住 Java 库的源代码吗?

关于java - 当桶中的条目对象从阈值减少后,JDK 8中的hashmap是否会再次调整自身大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38045390/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com