HashMap最大容量为什么是2的32次方
2016-04-24 16:41
423 查看
//默认的桶数组大小 static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; //极限值(超过这个值就将threshold修改为Integer.MAX_VALUE(此时桶大小已经是2的31次方了),表明不进行扩容了) static final int MAXIMUM_CAPACITY = 1 << 30; //负载因子(请阅读下面体会这个值的用处) static final float DEFAULT_LOAD_FACTOR = 0.75f;
观察jdk中HashMap的源码,我们知道极限值为2的31次方。
void resize(int newCapacity) { Entry[] oldTable = table; int oldCapacity = oldTable.length; if (oldCapacity == MAXIMUM_CAPACITY) { threshold = Integer.MAX_VALUE;//将threshold置为Integer.MAX_VALUE return;//当HashMap的容量已经是2的31次方的时候,直接返回。 } Entry[] newTable = new Entry[newCapacity]; transfer(newTable); table = newTable; threshold = (int)(newCapacity * loadFactor); }
观察jdk中源码可发现当HashMap的容量已经是2的31次方的时候,就不会在进行扩容了。
/** * The next size value at which to resize (capacity * load factor). * @serial */ int threshold;
如上为对threshold的定义。
/** * Adds a new entry with the specified key, value and hash code to * the specified bucket. It is the responsibility of this * method to resize the table if appropriate. * * Subclass overrides this to alter the behavior of put method. */ void addEntry(int hash, K key, V value, int bucketIndex) { Entry<K,V> e = table[bucketIndex]; table[bucketIndex] = new Entry<K,V>(hash, key, value, e); if (size++ >= threshold) resize(2 * table.length); }
观察如上源码可知,当添加完元素后的容量大于threshold,就调用resize方法。
相关文章推荐
- 【编程练习】poj1111
- 第 18 章 轮播插件
- 20145236 《Java程序设计》第八周学习总结
- centos7下使用yum安装mysql
- Android进阶笔记17:Android手机屏幕坐标系
- 25个常用的linux基础命令
- Android开发之Mac下抓包
- Eclipse界面重置
- 如何用常规手段优化大数据量网页加载速度
- linux 命令
- 冲刺阶段第六天
- PHP函数
- 剑指offer--重建二叉树
- android floating action button
- C++ new分配失败运行机制
- 最小生成树计数 bzoj 1016
- C/C++中inline/static inline/extern inline的区别及使用
- Android Studio技巧
- 求N的N阶乘的尾数(一道找规律的题目)
- MVC razor 中 RenderPartial, RenderAction , Partial , Action 的使用选择(基本用法)