本文介绍了默认容量为16的HashMap可以包含多于11/16个对象而不需要重新散列 - 这是正确的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是。



从这个问题我知道 HashMap 的初始容量默认为16,在调整大小之前最多允许11个条目因为默认加载因子是0.75。


  1. 何时进行重新刷新?数组中的11个条目或其中一个链接列表中的11个条目之后?因为数组大小为16,所以 HashMap 可能包含只要数组大小小于或等于11,就可以在链表中包含多个对象(可能多于16个)。因此,默认容量为16的 HashMap 可以包含更多比11/16对象没有反转 - 是这样吗?



解决方案





相反,它使用size(),所以size()是只有一件事情决定什么时候重新刷新,不管它是如何安排的。



来自Java 8的源码

  final void putMapEntries(Map  m,boolean evict){
int s = m.size(); ((float)s / loadFactor)+ 1.0F;(b)如果(s> 0){
if(table == null){//预大小
float ft =((float)s / loadFactor)
int t =((ft (int)ft:MAXIMUM_CAPACITY); (t>阈值)
threshold = tableSizeFor(t);
}
else if(s> threshold)
resize();


This is a followup question to What is the initial size of Array in HashMap Architecture?.

From that question I understand the initial capacity of HashMap is 16 by default which allows up to 11 entries before resizing since the default load factor is 0.75.

  1. When does the rehashing take place? After 11 entries in the array or 11 entries in one of the linked lists? I think after 11 entries in the array.

  2. Since the array size is 16 a HashMap could contain many objects (maybe more than 16) in a linked list as long as the array size is less than or equal to 11. Hence, a HashMap with default capacity 16 can contain more than 11/16 objects without rehashing - is this right?

解决方案

This is an obvious flaw in using the number of buckets occupied as a measure. Another problem is that you would need to maintain both a size and a number of buckets used.

Instead it's the size() which is used so the size() is the only thing which determines when rehashing occurs no matter how it is arranged.

From the source for Java 8

final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
    int s = m.size();
    if (s > 0) {
        if (table == null) { // pre-size
            float ft = ((float)s / loadFactor) + 1.0F;
            int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                     (int)ft : MAXIMUM_CAPACITY);
            if (t > threshold)
                threshold = tableSizeFor(t);
        }
        else if (s > threshold)
            resize();

这篇关于默认容量为16的HashMap可以包含多于11/16个对象而不需要重新散列 - 这是正确的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 15:22