HashMap底层是数组,数组里存储的是链表(单向链表或双向链表【红黑树】)
//简要摘录HashMap源码以便理解 public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable { static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; //默认主数组长度16 static final int MAXIMUM_CAPACITY = 1 << 30;//主数组最大长度 static final float DEFAULT_LOAD_FACTOR = 0.75f;//默认加载因子 static final int TREEIFY_THRESHOLD = 8; static final int MIN_TREEIFY_CAPACITY = 64; transient Node<K,V>[] table;//底层主数组 transient int size;//元素的数量 int threshold;//表示数组扩容门槛 final float loadFactor;//运行时加载因子 transient Set<Map.Entry<K,V>> entrySet; //空构造器 public HashMap() { this.loadFactor = DEFAULT_LOAD_FACTOR; //设置加载因子 } //带参构造器 public HashMap(int initialCapacity) { this(initialCapacity, DEFAULT_LOAD_FACTOR); } //带参构造器 public HashMap(int initialCapacity, float loadFactor) { this.loadFactor = loadFactor;//设置加载因子 this.threshold = tableSizeFor(initialCapacity);//比它大的最近的2的幂 } public V put(K key, V value) { return putVal(hash(key), key, value, false, true); } //计算key的哈希值 并二次散列 static final int hash(Object key) { int h; //二次散列 return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); } final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) { Node<K,V>[] tab; Node<K,V> p; int n, i; if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length;//首次添加,初始化主数组 长度n=16 //求余hash%n,计算存放位置下标i,该位置值取出赋给p if ((p = tab[i = (n - 1) & hash]) == null) //如果p为null tab[i] = newNode(hash, key, value, null);//封装为对象后赋给该下标 else { //如果p不为null,即该下标已有数据 Node<K,V> e; K k; //如果p的hash与key都与新值相同(出现哈希碰撞) if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) e = p;//p赋给e else if (p instanceof TreeNode) e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); else { //遍历链表 for (int binCount = 0; ; ++binCount) { //尾插法 if ((e = p.next) == null) {//如果没有下一个即是最后一个 p.next = newNode(hash, key, value, null);//封装为对象 赋给最后一个的next //如果链表长度大于等于7 (8-1) if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st treeifyBin(tab, hash);//扩容并重新安放各个元素 break; } //如果下一个的hash与key都与新值相同(出现哈希碰撞) if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) break;//中断遍历 去更新值 p = e;//继续下一个 } } if (e != null) { // existing mapping for key V oldValue = e.value;//保存旧值 if (!onlyIfAbsent || oldValue == null) e.value = value;//更新为新值 afterNodeAccess(e); return oldValue;//返回旧值 } } ++modCount; //集合元素数量加一,如果数量达到扩容门槛 if (++size > threshold) resize();//扩容 return null; } final Node<K,V>[] resize() { Node<K,V>[] oldTab = table; int oldCap = (oldTab == null) ? 0 : oldTab.length; int oldThr = threshold; int newCap, newThr = 0; //如果旧容量大于0 非首次添加 if (oldCap > 0) { //如果旧容量大于最大容量 if (oldCap >= MAXIMUM_CAPACITY) { threshold = Integer.MAX_VALUE; 扩容门槛设为int最大值 return oldTab;//返回传入的旧主数组 即不再进行后续扩容 }//新容量取旧容量的2倍 32,如果旧容量大于或等于16,新扩容门槛取旧扩容门槛的2倍 24 else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY) newThr = oldThr << 1; // double threshold } else if (oldThr > 0) // initial capacity was placed in threshold newCap = oldThr; else { //首次添加时,取默认初始数组容量 16 newCap = DEFAULT_INITIAL_CAPACITY; //默认加载因子计算扩容门槛 12 newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); } if (newThr == 0) { float ft = (float)newCap * loadFactor; newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ? (int)ft : Integer.MAX_VALUE); } threshold = newThr;//设置扩容门槛 @SuppressWarnings({"rawtypes","unchecked"}) Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];//初始化主数组 长度为newCap table = newTab; if (oldTab != null) {//如果旧主数组不为空 for (int j = 0; j < oldCap; ++j) {//遍历旧主数组 Node<K,V> e; if ((e = oldTab[j]) != null) {//如果该位置有值 oldTab[j] = null; if (e.next == null)//如果该位置链表下一个为空 即该位置是链表只有一个节点 newTab[e.hash & (newCap - 1)] = e;// 求余hash%newCap 取新数组的下标 将链表赋给新数组的该下标位置 else if (e instanceof TreeNode) ((TreeNode<K,V>)e).split(this, newTab, j, oldCap); else { // preserve order //如果下一个存在,即链表有多个节点 Node<K,V> loHead = null, loTail = null; Node<K,V> hiHead = null, hiTail = null; Node<K,V> next; do { next = e.next;//取链表下一节点赋给next //根据hash把链表节点分为低区、高区2部分 if ((e.hash & oldCap) == 0) {//坐落在低区 if (loTail == null) loHead = e;//低区链表的头节点 else loTail.next = e; loTail = e; } else { //坐落在高区 if (hiTail == null) hiHead = e;//高区链表的头节点 else hiTail.next = e; hiTail = e; } } while ((e = next) != null); if (loTail != null) {//如果有坐落在低区的节点 loTail.next = null;//尾部截断 newTab[j] = loHead;//低区链表头结点放到j位 } if (hiTail != null) {//如果有坐落在高区的节点 hiTail.next = null;//尾部截断 newTab[j + oldCap] = hiHead;//高区链表头结点放到j+oldCap位 } } } } } return newTab; } final void treeifyBin(Node<K,V>[] tab, int hash) { int n, index; Node<K,V> e; //如果底层数组为null或长度小于 64 if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY) resize();//扩容数组 else if ((e = tab[index = (n - 1) & hash]) != null) { TreeNode<K,V> hd = null, tl = null; do { //替换为红黑树 TreeNode<K,V> p = replacementTreeNode(e, null); if (tl == null) hd = p; else { p.prev = tl; tl.next = p; } tl = p; } while ((e = e.next) != null); if ((tab[index] = hd) != null) hd.treeify(tab); } } }
//获取比cap大的最近的2的幂 static final int tableSizeFor(int cap) { int n = cap - 1; n |= n >>> 1;//等价于 n = n | (n >>> 1) 即二进制格式低位全部置1, n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16; return (n < 0) ? 1 : n + 1; }
举例数字8,其二进制格式变化过程如下图:其结果位原数字低位全部置1,公式最后又加了1,所以最终结果为大于自己的最近的2的幂 16