HashMap源码阅读(不包括红黑树部分)

188 阅读7分钟

       HashMap主要是有数组+链表的结构实现的,相当于数组中的每个元素都维护了一个链表。
        在JDK1.8中,引入了红黑树,当链表长度大于8时会变成红黑树的结构,当红黑树中的元素数量小于6时又会变回链表结构。
        其实初学者的话不需要去了解红黑树的部分,只要了解到数组+链表这一层,就已经算是对HashMap有一定认识了,探索过深反而得 不偿失。

首先呢,先来认识几个常量
//数组的默认长度为2^4=16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; 

 
//数组的最大长度为2^30=1073741824
static final int MAXIMUM_CAPACITY = 1 << 30;


//加载因子的默认值为0.75,加载因子的用途下文会解释
static final float DEFAULT_LOAD_FACTOR = 0.75f;


//当链表存在多少个元素时,需要转化为红黑树
static final int TREEIFY_THRESHOLD = 8;


//当红黑树的元素数量少于多少时,需要转化为链表
static final int UNTREEIFY_THRESHOLD = 6;


//红黑树的最小长度,也就是链表转化为红黑树时,会直接扩容到64
static final int MIN_TREEIFY_CAPACITY = 64;


然后再来看一下几个成员变量和构造方法
/*
*数组中的Node有两种,一种是链表的节点,也就是Node,另外一种是红黑树的节点,
*也就是TreeNode。
*链表的节点包括哈希值、key、value、后继
*/
static class Node<K,V> implements Map.Entry<K,V> {
    final int hash;
    final K key;
    V value;
    Node<K,V> next;
}

//而红黑树的节点包括父节点、左孩子、右孩子、颜色
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
    TreeNode<K,V> parent;  // red-black tree links
    TreeNode<K,V> left;
    TreeNode<K,V> right;
    TreeNode<K,V> prev;    // needed to unlink next upon deletion
    boolean red;
}


//hash数组
transient Node<K,V>[] table;

//键值对
transient Set<Map.Entry<K,V>> entrySet;

//当前hashMap含有多少个元素
transient int size;

//当前HashMap的修改次数
transient int modCount;

//加载因子
final float loadFactor;

//当 size >= threshold 时就需要对数组执行扩容操作了
//threshold = capacity(当前容量) * loadFactor(加载因子)
int threshold;


//两个参数的构造函数,用户可以设置初始容量和加载因子,从而计算出threshold
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);
    this.loadFactor = loadFactor;
    this.threshold = tableSizeFor(initialCapacity);
}


//一个参数的构造函数,用户可以自定义初始容量,加载因子默认为0,75
public HashMap(int initialCapacity) {
    this(initialCapacity, DEFAULT_LOAD_FACTOR);
}


//无参构造函数,加载因子默认为0.75
public HashMap() {
    this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}

下面是对put方法的分析
//前三个参数分别为通过key算出的Hash值、Key、Value后面两个参数暂时不需要理解
public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}

//Hash值的算法为取hashCode并且移位,然后取余,用这种方式减少hash冲突
static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

//下面就是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;
    if ((tab = table) == null || (n = tab.length) == 0)
//如果当前hashmap为空,那么直接扩容,得到n为当前可用长度
        n = (tab = resize()).length;
    if ((p = tab[i = (n - 1) & hash]) == null)
//通过hash值与n-1进行与运算,得到一个必然小于n的整数
//若数组的该索引下的元素为空,那么直接将节点加进去。
        tab[i] = newNode(hash, key, value, null);
    else {
        Node<K,V> e; K k;
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
//如果当前要put的key已经存在与hashmap中,则覆盖
            e = p;
        else if (p instanceof TreeNode)
//如果发现p是一个红黑树,那么以红黑树的方式添加当前节点
            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);
                    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;
            }
        }
        if (e != null) { // existing mapping for key
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    ++modCount;

//如果当前hashmap长度>threshold则开始扩容操作
    if (++size > threshold)
        resize();

    afterNodeInsertion(evict);
    return null;
}


跟put相比,get方法就要简单很多了

下面的逻辑看上去比较乱,实际上思路很简单。

首先,通过hash算出的索引值可以直接找到位于数组的元素,我们都知道数组的查找效率是O(1)的。

接着,判断一下这个元素是不是没有后继,也就是只存在一个节点,那么直接返回

最后,判断这个元素是链表的节点还是红黑树的节点、如果是链表,那么遍历链表,找到key一样的,然*后返回,如果是红黑树,则按照红黑树的方式去寻找。

public V get(Object key) {
    Node<K,V> e;
    return (e = getNode(hash(key), key)) == null ? null : e.value;
}
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 && // always check first node
            ((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 {
               //如果不是红黑树,遍历链表,找key的所属节点
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    return e;
            } while ((e = e.next) != null);
        }
    }
    return null;
}


下面是扩容的部分

        当发生扩容操作时,如果说旧数组已经到了数组最大长度了,那么则不继续扩容了,任由它hash碰撞。否则会创建一个新的数组,长度为旧数组的两倍,然后把旧数组的元素放到新数组里。比方说旧数组的长度为len,旧数组的某个元素下标为index,新数组的长度为index*2,旧数组的元素要么停留在index,要么会移位到index+len的位置。

        那么是根据什么来判断是否移位呢,hashmap中实现的算法非常巧妙,是根据当前新数组最高位的二进制数字判断的,也就是(oldhash&index),若这个值为0,则停留在原地不动,若这个值不为零,那么则移位。

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;
    //创建长度为旧数组两倍的新数组
    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;
                        //如果值为0,那么这个元素停留在原地
                        if ((e.hash & oldCap) == 0) {
                            if (loTail == null)
                                loHead = e;
                            else
                                loTail.next = e;
                            loTail = e;
                        }
                        //如果值不为0,那么则移位到index+len中
                        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;
}



本文只作为学习过程中的随笔,如果有不正确的地方欢迎指出。



参考文章  tech.meituan.com/2016/06/24/…