HashMap源码分析

HashMap的节点

// 基础节点,单链表
static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;

        Node(int hash, K key, V value, Node<K,V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }

        public final K getKey()        { return key; }
        public final V getValue()      { return value; }
        public final String toString() { return key + "=" + value; }

        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

        public final boolean equals(Object o) {
            if (o == this)
                return true;
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                if (Objects.equals(key, e.getKey()) &&
                    Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }
    }


// 树节点
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;
        TreeNode(int hash, K key, V val, Node<K,V> next) {
            super(hash, key, val, next);
        }
        //返回当前节点的根节点
        final TreeNode<k,v> root() {
          for (TreeNode<k,v> r = this, p;;) {
            if ((p = r.parent) == null)
                return r;
            r = p;
          }
        }
        // 省略代码....
}

 

初始参数

public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable {
    // 序列号
    private static final long serialVersionUID = 362498820763181265L;    
    // 默认的初始容量是16
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;   
    // 最大容量
    static final int MAXIMUM_CAPACITY = 1 << 30; 
    // 默认的填充因子
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    // 当桶(bucket)上的结点数大于这个值时会转成红黑树
    static final int TREEIFY_THRESHOLD = 8; 
    // 当桶(bucket)上的结点数小于这个值时树转链表
    static final int UNTREEIFY_THRESHOLD = 6;
    // 桶中结构转化为红黑树对应的table的最小大小
    static final int MIN_TREEIFY_CAPACITY = 64;
    // 存储元素的数组,总是2的幂次倍
    transient Node<k,v>[] table; 
    // 存放具体元素的集
    transient Set<map.entry<k,v>> entrySet;
    // 存放元素的个数,注意这个不等于数组的长度。
    transient int size;
    // 每次扩容和更改map结构的计数器
    transient int modCount;   
    // 临界值 当实际大小(容量*填充因子)超过临界值时,会进行扩容
    int threshold;
    // 填充因子
    final float loadFactor;
}

// 获取大于cap的最小的二次幂数值
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;
    }

HashMap构造方法

// 最常用的无参构造 
public HashMap() {
    this.loadFactor = DEFAULT_LOAD_FACTOR; // 设置为0.75f,扩容因子
}

/** 构造方法2,将已经存在的map复制到新的map,扩容因子也是默认值,但是复制的时候可能会重算 */
public HashMap(Map<? extends K, ? extends V> m) {
    this.loadFactor = DEFAULT_LOAD_FACTOR;
    putMapEntries(m, false);
}

// 构造方法3 引用了构造方法4,扩容因子是默认值
public HashMap(int initialCapacity) {
    this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

// 构造方法4 自定义初始容量和扩容因子
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);
    }

resize方法

重置容量,增加元素的时候可能触发(进行重置的时候,如果触发了扩容,会将原有的数据重新分配)

final Node<K,V>[] resize() {
    Node<K,V>[] oldTab = table; // table就是hashMap的主数组结构
    int oldCap = (oldTab == null) ? 0 : oldTab.length;
    int oldThr = threshold;
    int newCap, newThr = 0;
//大于0代表数组已经初始化了 
    if (oldCap > 0) {
// 判断是否是最大允许值,如果是,则不进行扩容,但是把阈值设置为int最大
        if (oldCap >= MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return oldTab;
        }
// 将进行容量和阈值的2倍扩容(旧的容量要大于16)
        else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                 oldCap >= DEFAULT_INITIAL_CAPACITY)
            newThr = oldThr << 1; // double threshold
    }
//table为空,将阈值赋值给新的容量大小,在后续创建
    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);
    }
// 新的阈值为0时,有可能是扩容之后大于最大值,重算,loadFactor因子在初始化的时候必然有初始值
    if (newThr == 0) {
        float ft = (float)newCap * loadFactor;
        newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                  (int)ft : Integer.MAX_VALUE);
    }
// 设置新的阈值,创建新的Node数组
    threshold = newThr;
    @SuppressWarnings({"rawtypes","unchecked"})
    Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
    table = newTab;
// oldTab不为空(其实就是hashmap增加元素触发的扩容),遍历每个元素
    if (oldTab != null) {
        for (int j = 0; j < oldCap; ++j) {
            Node<K,V> e;
            if ((e = oldTab[j]) != null) {
        // 如果节点存在链表,保存到e,原始数组元素清空
                oldTab[j] = null;
        // 如果是链表是单节点
                if (e.next == null)
    //直接重算hash对应位置
                    newTab[e.hash & (newCap - 1)] = e;
        // 如果原始数据是红黑树,进行split处理
                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;
                       //  这里跟oldCap比较,就是未扩容前的容器大小,在新容器中就是低位数据 
                        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;
}

查询元素get

public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
}

通过key的hash值找到所在Node的数组位置,然后将对应位置的链表取出来分析

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 && // 先查找链表第一个位置的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);
            }
        }
        return null;
    }

其中(n - 1) & hash 等价于对map的长度取余数,相当于计算散列到具体位置

 

插入元素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;
        // 当数组列表table为空时,通过resize方法初始
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        // 如果所在的数组位置没有链表,则直接插入新的节点元素
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            // 如果key是链表的第一个元素,则直接更新值
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            // 如果是红黑树,则使用树的插入
            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);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    // 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();
        afterNodeInsertion(evict);
        return null;
    }

通过源码看出,传参的onlyIfAbsent标识在key存在的情况下,oldValue只有为null才更新值

1、当数组列表table为空时,通过resize方法初始。否则判断插入的数据key是否存在

2、如果所在的数组位置没有链表,则直接插入新的节点元素,否则往下

3、如果key是链表的第一个元素,则直接更新值,否则往下

4、判断是否是TreeNode(红黑树,暂时未知处理逻辑),是的直接调用TreeNode的putTreeVal方法,否则往下

5、遍历链表的每一个元素,查看key是否已经存在链表中,如果存在则直接更新值,不存在则在链表最后增加新的元素,并且如果链表元素大于8个,链表需要转换为树结构。

移除元素

移除元素的逻辑跟插入元素的判断逻辑是相似的,具体看代码注释解析

public V remove(Object key) {
    Node<K,V> e;
    return (e = removeNode(hash(key), key, null, false, true)) == null ?
        null : e.value;
}

//主体的移除节点方法,matchValue为true是用于判断key相等的情况,value相等才删除
final Node<K,V> removeNode(int hash, Object key, Object value,
                           boolean matchValue, boolean movable) {
    Node<K,V>[] tab; Node<K,V> p; int n, index;
    //table不为空且table长度大于0且hash值对应的table节点不为空
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (p = tab[index = (n - 1) & hash]) != null) {
        Node<K,V> node = null, e; K k; V v;
        // 如果数组对应链表的第一个元素就匹配了删除的key,则记录node的位置
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            node = p;
        //如果第一个元素不是,先判断是否是红黑树
        else if ((e = p.next) != null) {
            // 红黑树的获取key
            if (p instanceof TreeNode)
                node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
            // 链表循环获取找到对应的key
            else {
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key ||
                         (key != null && key.equals(k)))) {
                        node = e;
                        break;
                    }
                    p = e;
                } while ((e = e.next) != null);
            }
        }
        // matchValue为true是用于判断key相等的情况,value相等才删除
        if (node != null && (!matchValue || (v = node.value) == value ||
                             (value != null && value.equals(v)))) {
            if (node instanceof TreeNode)
                ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
            // 第一个链表节点匹配的情况
            else if (node == p)
                // 相当于直接将第一个元素去掉,指向下一个元素或者空
                tab[index] = node.next;
            // 这种情况下,p是目标节点的上位节点,
            else
                p.next = node.next;
//modCount用于检测是否被修改,线程不安全,不符合预期的结果会报错
            ++modCount;
            --size;
            afterNodeRemoval(node);
            return node;
        }
    }
    return null;
}

HashMap线程不安全

在源码中,可以看到有一个属性modCount在很多地方都有出现(上述的remove相关方法也能看到),这个属性用于迭代器Iterator开始迭代的时候,检测是否发生了改变。 modCount 变量声名为 transient,不参与序列化的过程。在hashmap中,put、remove、clear等方法执行时modCount都会自增。

在hashmap中,所有遍历的方法都会对modCount进行检验,在循环之前先保存modCount的原始值,循环之后再查看是否相等,不相等代表其他线程影响了该值,直接抛出ConcurrentModificationException异常。

public final void forEach(Consumer<? super K> action) {
            Node<K,V>[] tab;
            if (action == null)
                throw new NullPointerException();
            if (size > 0 && (tab = table) != null) {
                int mc = modCount;
                for (int i = 0; i < tab.length; ++i) {
                    for (Node<K,V> e = tab[i]; e != null; e = e.next)
                        action.accept(e.key);
                }
                if (modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }

HashMap的转化为树

final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
        if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
            resize();
        // 如果hash值在当前的数组位置的链表不为空,才树化
        else if ((e = tab[index = (n - 1) & hash]) != null) {
            TreeNode<K,V> hd = null, tl = null;
            do {
                // 将节点转为TreeNode
                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);
        }
}

//  将Node节点转为TreeNode
TreeNode<K,V> replacementTreeNode(Node<K,V> p, Node<K,V> next) {
    return new TreeNode<>(p.hash, p.key, p.value, next);
}

// 将链表转化为红黑树
final void treeify(Node<K,V>[] tab) {
            // 根节点
            TreeNode<K,V> root = null;
            for (TreeNode<K,V> x = this, next; x != null; x = next) {
                // 先记录下个节点的位置
                next = (TreeNode<K,V>)x.next;
                // 将节点的左右树都清空
                x.left = x.right = null;
                // 如果根节点为空,将当前节点设置为根节点,为黑节点,并且无父节点
                if (root == null) {
                    x.parent = null;
                    x.red = false;
                    root = x;
                }
                else {
                    K k = x.key;
                    int h = x.hash;
                    Class<?> kc = null;
                    for (TreeNode<K,V> p = root;;) {
                        // dir为-1代表左子树遍历,为1代表右子树遍历,ph是检索节点的hash值
                        int dir, ph;
                        K pk = p.key;
                        if ((ph = p.hash) > h)
                            dir = -1;
                        else if (ph < h)
                            dir = 1;
                        // 如果节点的hash值相同,则需要再进行进一步判断(未理解)
                        else if ((kc == null &&
                                  (kc = comparableClassFor(k)) == null) ||
                                 (dir = compareComparables(kc, k, pk)) == 0)
                            dir = tieBreakOrder(k, pk);
                        // 记录下遍历到的节点位置
                        TreeNode<K,V> xp = p;
                        // 遍历已生成的红黑树,将p设置为现在节点的左或右子树,
                        // 直到遍历到最终位置左子树或右子树为空的情况,才插入值
                        if ((p = (dir <= 0) ? p.left : p.right) == null) {
                            x.parent = xp;
                            if (dir <= 0)
                                xp.left = x;
                            else
                                xp.right = x;
                            root = balanceInsertion(root, x);
                            break;
                        }
                    }
                }
            }
            // 将红黑树的根节点存到table对应节点
            moveRootToFront(tab, root);
}

了解红黑树添加节点的平衡,先要知道二叉树左旋和右旋

以下是左旋代码实现

// 左旋
static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
                                              TreeNode<K,V> p) {
            //这里的p即上图的A节点,r指向右孩子即C,rl指向右孩子的左孩子即D,pp为p的父节点
            TreeNode<K,V> r, pp, rl;
            if (p != null && (r = p.right) != null) {
                // 将需要进行左旋的右孩子的左孩子放到p的右节点(即将上图D移到A的右边),并且记录为rl
                if ((rl = p.right = r.left) != null)
                    rl.parent = p;
                // 将p的父节点变为r的父节点,相当于上图的C上移到A的位置
                if ((pp = r.parent = p.parent) == null)
                    // 如果p的父节点为空,则代表是根节点,变为黑色
                    (root = r).red = false;
                // 如果p不是根节点,判断p在开始时是属于左节点还是右节点,然后对应变更位置
                else if (pp.left == p)
                    pp.left = r;
                else
                    pp.right = r;
                r.left = p;
                p.parent = r;
            }
            return root;
        }
// 右旋
static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
                                               TreeNode<K,V> p) {
            //这里的p即上图的A节点,l指向左孩子即C,lr指向左孩子的右孩子即E,pp为p的父节点
            TreeNode<K,V> l, pp, lr;
            if (p != null && (l = p.left) != null) {
                if ((lr = p.left = l.right) != null)
                    lr.parent = p;
                if ((pp = l.parent = p.parent) == null)
                    (root = l).red = false;
                else if (pp.right == p)
                    pp.right = l;
                else
                    pp.left = l;
                l.right = p;
                p.parent = l;
            }
            return root;
        }

红黑树的插入操作

static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
                                                    TreeNode<K,V> x) {
            x.red = true;
            for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
                //情景1:父节点为null
                if ((xp = x.parent) == null) {
                    x.red = false;
                    return x;
                }
          //情景2,3:父节点是黑色节点或者祖父节点为null
                else if (!xp.red || (xpp = xp.parent) == null)
                    return root;
          //情景4:插入的节点父节点和祖父节点都存在,并且其父节点是祖父节点的左节点
                if (xp == (xppl = xpp.left)) {
            //情景4i:插入节点的叔叔节点是红色
                    if ((xppr = xpp.right) != null && xppr.red) {
                        xppr.red = false;
                        xp.red = false;
                        xpp.red = true;
                        x = xpp;
                    }
            //情景4ii:插入节点的叔叔节点是黑色或不存在
                    else {
              //情景4iia:插入节点是其父节点的右孩子
                        if (x == xp.right) {
                            root = rotateLeft(root, x = xp);
                            xpp = (xp = x.parent) == null ? null : xp.parent;
                        }
              //情景4iib:插入节点是其父节点的左孩子
                        if (xp != null) {
                            xp.red = false;
                            if (xpp != null) {
                                xpp.red = true;
                                root = rotateRight(root, xpp);
                            }
                        }
                    }
                }
          //情景5:插入的节点父节点和祖父节点都存在,并且其父节点是祖父节点的右节点
                else {
            //情景5i:插入节点的叔叔节点是红色
                    if (xppl != null && xppl.red) {
                        xppl.red = false;
                        xp.red = false;
                        xpp.red = true;
                        x = xpp;
                    }
            //情景5ii:插入节点的叔叔节点是黑色或不存在
                    else {
·              //情景5iia:插入节点是其父节点的左孩子 
                        if (x == xp.left) {
                            root = rotateRight(root, x = xp);
                            xpp = (xp = x.parent) == null ? null : xp.parent;
                        }
              //情景5iib:插入节点是其父节点的右孩子
                        if (xp != null) {
                            xp.red = false;
                            if (xpp != null) {
                                xpp.red = true;
                                root = rotateLeft(root, xpp);
                            }
                        }
                    }
                }
            }
        }
 

若有

原文地址:https://www.cnblogs.com/snake23/p/10422775.html