HashMap源码解读(二)

1.前言

上次的博客,主要讲了HashMap的数据结构,没有详细的阐述HashMap的具体实现。在这次的博客中通过阐述put()方法和get()方法来阐述HashMap怎么实现的。

2.put方法

public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
        boolean evict) {
    Node<K, V>[] tab;
    Node<K, V> p;
    int n, i;
    // 判断HashMap的table是否是空或者长度为0,执行resize操作
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
    // (n - 1) & hash 计算在table表中的下标的值
    // 此处的table为空
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    else {
        Node<K, V> e;
        K k;
        // hash冲突,key相等
        if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
        // p是TreeNode的,调用putTreeVal方法添加TreeNode
        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);
                    // 如果binCount大于TREEIFY_THRESHOLD,进行树化操作
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        treeifyBin(tab, hash);
                    break;
                }
                if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))
                    break;
                p = e;
            }
        }
            // 要插入的结点和之前的结点有相同的key值,覆盖原先的结果
        if (e != null) { // existing mapping for key
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    ++modCount;
    // 如果超过阈值,执行resize操作
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}

通过上面的代码我们知道,put方法主要的实现是putVal方法,putVal方法的具体过程如下

  • 判断HashMap的table的长度是否为0还是null,是的话执行resize操作
  • 接着计算下该Hash值在table表中的下标,是否后结点Node,没有结点Node,直接调用new Node()方法生成Node结点插入该表中。
  • 如果在该下标处存在Node结点,则判断是否是TreeNode,如果是TreeNode,则执行putTreeVal方法。
  • 尾插法插入结点,如果改下标处的Node的结点的数量超过TREEIFY_THRESHOLD,则把Node结点树化成TreeNode结点。
  • 如果插入的结点和之前的结点有相同的key值,覆盖原先的结果。
  • 如果size超过阈值则进行resize操作。

在put函数中我们提到了resize操作,resize操作究竟是什么呢?让我们继续进行源码的阅读:

    /**
     * HashMap的扩容方法,两次幂次展开,每箱的元素放在相同索引出或者以旧表长度为偏移量移动新表
     */
final Node<K,V>[] resize() {
    Node<K,V>[] oldTab = table;
    int oldCap = (oldTab == null) ? 0 : oldTab.length;
    int oldThr = threshold;
    int newCap, newThr = 0;
    //判断oldCap的容量
    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) // 初始容量被放入阈值
        newCap = oldThr;
    else {               // 零初始化阈值用默认值
        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"})
    //重建table
    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;
                //如果结点是TreeNode结点,那么执行split方法
                else if (e instanceof TreeNode)
                    ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                else { // 将该链表分成两个链表,低下标链表,高下标链表
                    Node<K,V> loHead = null, loTail = null;
                    Node<K,V> hiHead = null, hiTail = null;
                    Node<K,V> next;
                    do {
                        next = e.next;
                //如果e.hash&oldCap==0,原来容量新增的那个bit为0,保持原索引
                        if ((e.hash & oldCap) == 0) {
                            if (loTail == null)
                                loHead = e;
                            else
                                loTail.next = e;
                            loTail = e;
                        }
                          //如果e.hash&oldCap==1,原来容量新增的那个bit为1,原索引+oldCap为新位置
                        else {
                            if (hiTail == null)
                                hiHead = e;
                            else
                                hiTail.next = e;
                            hiTail = e;
                        }
                    } while ((e = next) != null);
                        //原索引放到bucket中
                    if (loTail != null) {
                        loTail.next = null;
                        newTab[j] = loHead;
                    }
                    //原索引+oldCap放到bucket中
                    if (hiTail != null) {
                        hiTail.next = null;
                        newTab[j + oldCap] = hiHead;
                    }
                }
            }
        }
    }
    return newTab;
}

关于resize的扩容部分的具体解释,参照了美团技术团队的一篇文章《Java 8系列之重新认识HashMap》具体如图所示:
这里写图片描述
根据上图我们知道:
原来两个的下标都是9,后来经过扩容后Key1的下标还是9,而Key2的下标变为9+16=25。

3. get方法

我们在使用HashMap的时候,除了用put方法来放置我们的键值对,而且我们还使用get方法来根据我们的key值来取相关的值。首先来看代码:

public V get(Object key) {
    Node<K,V> e;
    return (e = getNode(hash(key), key)) == null ? null : e.value;
}
 /**
 * HashMap的getNode方法
 * @param hash hash for key
 * @param key the key
 * @return the node, or null if none
 * 判断Hash值,然后判断key值,最后再判断key.equal
 */
 final Node<K,V> getNode(int hash, Object key) {
    Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (first = tab[(n - 1) & hash]) != null) {
        if (first.hash == hash && // 总是返回第一个结点
            ((k = first.key) == key || (key != null && key.equals(k))))
            return first;
        //第一个结点不符合的话,判断后面的结点。
        if ((e = first.next) != null) {
            if (first instanceof TreeNode)
                return ((TreeNode<K,V>)first).getTreeNode(hash, key);
            do {
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    return e;
            } while ((e = e.next) != null);
        }
    }
    //所有结点都不符合的话,返回null
    return null;
}

相比于put方法,get方法在我们看来纯粹就是小巫见大巫了,其中的基本思想如下:

  • 先计算key对应的Hash值
  • 然后找到在table中的下标
  • 如果第一个结点的hash值相等的话,比对key值,如果相等返回该结点
  • 根据链表从后往前找,找到hash值和key值都相等的就返回
  • 如果都没有找到返回null

4.计算Hash的方法

static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

它的思想也比较简单:

  • 如果key==null,返回0
  • 计算key的HashCode记为h
  • 取h的高16位与h本身进行异或运算,即为key的Hash值

猜你喜欢

转载自blog.csdn.net/zhanghanlun/article/details/80077862