理解HashMap
来源:互联网 发布:意大利古典家具 知乎 编辑:程序博客网 时间:2024/05/23 12:42
所有的构造函数都会重载到下面这个构造函数
当length(当前容量)为指数2的幂时,h(hashCode)&(length-1) = h%length(貌似求余是所有计算效率最低的) 推导:
/** * Constructs an empty <tt>HashMap</tt> with the specified initial * capacity and load factor. * * @param initialCapacity the initial capacity * @param loadFactor the load factor * @throws IllegalArgumentException if the initial capacity is negative * or the load factor is nonpositive */ public HashMap(int initialCapacity, float loadFactor) { if (initialCapacity < 0) throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity); if (initialCapacity > MAXIMUM_CAPACITY) initialCapacity = MAXIMUM_CAPACITY; if (loadFactor <= 0 || Float.isNaN(loadFactor)) throw new IllegalArgumentException("Illegal load factor: " + loadFactor); // Find a power of 2 >= initialCapacity int capacity = 1; while (capacity < initialCapacity) capacity <<= 1; this.loadFactor = loadFactor; threshold = (int)Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1); table = new Entry[capacity]; useAltHashing = sun.misc.VM.isBooted() && (capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD); init(); }
里面的capability一定为指数2的幂(原因是为了方便求Hash值)
HashMap内部实现是一个动态数组,所以当需要的容量超过容器现有的容量需要扩容(每次扩容为原来1倍),所以threshold是用来衡量是否需要扩容的标准。threshold等于capacity*loadFactor 且不大于max_capacity+1(loadFactor默认为0.75, 空间和时间之间的权衡)。
每次增删查移动时候都会先算hashcode求,再求index(指向table位置的hash),调用静态函数indexFor
/** * Returns index for hash code h. */ static int indexFor(int h, int length) { return h & (length-1); }
当length(当前容量)为指数2的幂时,h(hashCode)&(length-1) = h%length(貌似求余是所有计算效率最低的) 推导:
当length等于2^n时, h大于length的位数一定可以被h整除剩下一定是余数所以h-1&剩下的就直接可以把余数取出来了
0 0
- 理解HashMap
- 理解HashMap
- 理解HashMap
- HashMap 理解
- 理解HashMap
- 理解HashMap
- hashMap理解
- HashMap理解
- HashMap理解
- HashMap理解
- 深入理解HashMap
- 深入理解HashMap
- [zt] 深入理解HashMap
- 深入理解HashMap
- 深入理解HashMap
- 深入理解HashMap
- Hashmap的深入理解
- 深入理解HashMap
- 预处理、const与sizeof
- tomcat 数据源和连接池配置 server.xml 中加中文注释
- FOJ 1752 && FOJ 1759 (a^b%c 的不同情况)
- iOS开发- 隐藏状态栏(电池栏)
- LeetCode | Single Number(数组中的单个数字)
- 理解HashMap
- 我的算法学习之路
- 用yum给CentOS安装gcc
- try catch finally 与 return 的问题
- Window Classes
- hrbustoj1212 乘积最大 区间DP
- VS2010开发web项目打开后,项目不可用,提示“需要缺少的 Web 组件才能进行加载”
- POJ 1004 Financial Management(水题)
- Java 之 volatile 解析