HashMap源码笔记

141 阅读6分钟

HashMap源码

构造方法

HashMap<String, Integer> hashMap = new HashMap<String, Integer>(14);
 // 我给定初始容量为14,这是不符合要求的,但是源码中会做处理

public HashMap(int initialCapacity, float loadFactor) {     // 初始容量、装载因子
        if (initialCapacity < 0)   // 初始容量不为负数
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)  // 初始容量 的大小超过最大值(2的30次幂),则取最大值
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))  //装载因子为数字且不小于0
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        this.loadFactor = loadFactor;   
        this.threshold = tableSizeFor(initialCapacity);  // 调用方法处理初始容量
    }

tableSizeFor方法处理初始容量问题

    /**
     * Returns a power of two size for the given target capacity.
     */
    static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;   // >>>含义是 n转成二进制数,1为右移的次数,高位补0;
        n |= n >>> 2;   // | 按位或,有1即真
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }

说明:我设置的初始容量为14,根据执行的步骤:

n=13 -> 1101

n >>> 1的结果:

0110

n |= 0110的结果:

1111

根据这样的规律继续往下走,最后返回15+1。得到最终的结果为16

测试:

public class MapDemo {
​
    static final int MAXIMUM_CAPACITY = 1 << 30;
    
    public static void main(String[] args) {
        HashMap<String, Integer> hashMap = new HashMap<String, Integer>(14);
        System.out.println(tableSizeFor(14)); // 16
        System.out.println(tableSizeFor(17)); // 32
        System.out.println(tableSizeFor(3)); // 4
        System.out.println(tableSizeFor(5)); // 8
        System.out.println(tableSizeFor(9)); // 16
    }
    
    // 子定义初始容量转为2的幂,大于初始容量
    static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }
​
}

hash方法

// jdk1.8的hash方法
    // key.hashCode()  返回散列值
    // ^ 异或
    // >>> 无符号右移  
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

Hash算法本质上就是三步:取key的hashCode值、高位运算、取模运算。

在jdk1.8中,通过hashCode()的高16位异或低16位实现的:(h = k.hashCode()) ^ (h >>> 16),主要是从速度、功效、质量来考虑的,这么做可以在数组table的length比较小的时候,也能保证考虑到高低Bit都参与到Hash的计算中,同时不会有太大的开销。

示例:(n是数组的长度)

preview

在jdk1.7中,

static int indexFor(int h, int length) {  //jdk1.7的源码,jdk1.8没有这个方法,但是实现原理一样的
     return h & (length-1);  //第三步 取模运算
}
//它通过h & (table.length -1)来得到该对象的保存位,而HashMap底层数组的长度总是2的n次方,这是 
//HashMap在速度上的优化。当length总是2的n次方时,h& (length-1)运算等价于对length取模,也就是 
//h%length,但是&比%具有更高的效率

put方法

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
    // 判断table是否为空,或者length是否为0
        if ((tab = table) == null || (n = tab.length) == 0) 
            n = (tab = resize()).length;    // resize扩容
    // 根据计算的hash值得到插入的数组下标索引
        if ((p = tab[i = (n - 1) & hash]) == null)  
            tab[i] = newNode(hash, key, value, null); // 插入到tab[i]是否为链表这个桶中
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&  // 判断key是否已经存在
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)  // 判断tab[i]为是否为红黑树,是则直接插入
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {  
                // tab[i]为链表
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) { // 叶子节点
                        // next存放新插入的节点的地址
                        p.next = newNode(hash, key, value, null);
                        // 新增节点后,判断链表长度(binCount循环未完成暂未更新)是否大于8
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash); // 转为红黑树
                        break;
                    }
                    if (e.hash == hash && // 这种情况说明key 已经存在
                        ((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(); // 扩容
        afterNodeInsertion(evict);
        return null;
    }

img

resize扩容方法

jdk1.7中,

void resize(int newCapacity) {   //传入新的容量
    Entry[] oldTable = table;    //引用扩容前的Entry数组
    int oldCapacity = oldTable.length;         
    if (oldCapacity == MAXIMUM_CAPACITY) {  //扩容前的数组大小如果已经达到最大(2^30)了
        threshold = Integer.MAX_VALUE; //修改阈值为int的最大值(2^31-1),这样以后就不会扩容了
         return;
     }
  
    Entry[] newTable = new Entry[newCapacity];  //初始化一个新的Entry数组
    transfer(newTable);                         //将数据转移到新的Entry数组里
    table = newTable;                           //HashMap的table属性引用新的Entry数组
    threshold = (int)(newCapacity * loadFactor);//修改阈值
 }

transfer方法

void transfer(Entry[] newTable) {
    Entry[] src = table;                   //src引用了旧的Entry数组
    int newCapacity = newTable.length;
    for (int j = 0; j < src.length; j++) { //遍历旧的Entry数组
        Entry<K,V> e = src[j];             //取得旧Entry数组的每个元素
        if (e != null) {
            //释放旧Entry数组的对象引用(for循环后,旧的Entry数组不再引用任何对象)
            src[j] = null;
            do {
                Entry<K,V> next = e.next;
                int i = indexFor(e.hash, newCapacity); //!!重新计算每个元素在数组中的位置
                // 头插入法,先插入的节点反而在链表尾部
                e.next = newTable[i]; //标记[1]
                newTable[i] = e;      //将元素放在数组上
                e = next;             //访问下一个Entry链上的元素
            } while (e != null);
        }
    }
}

jdk1.8中:

final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table; // 保存原数组
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        if (oldCap > 0) {
            if (oldCap >= MAXIMUM_CAPACITY) { // 原容量已经达到最大容量,
                threshold = Integer.MAX_VALUE; // 调整阈值
                return oldTab;
            }
            // 扩容后的容量 小于  最大容量,原容量大于默认初始容量
            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 {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            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];
        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; // 直接再散列到新的数组的位置上
                    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;
                            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;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }