【Java集合类】HashMap源码分析(jdk1.8)

HashMap是基于哈希表实现的,每一个元素是一个key-value对。

目录

  • 数据结构
    • 存储形式
    • 初始化
    • 扩容
  • 查找操作
  • 插入操作
  • 删除操作

数据结构

首先,每个元素都有一个hash值,我们看看hash值是如何生成的:

/**
     * 将key的哈希值无符号右移16位与低16位的亦或运算。
     * 作用:如果key数量较少,高16位的哈希值基本固定不变。将高16位
     * 的哈希值也参与运算,使哈希值分布更均匀,减少hash碰撞
     */
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

原理具体分析见:HashMap源码注解 之 静态工具方法hash()、tableSizeFor()(四)

存储形式

HashMap的数据结构采用数组+单链表+红黑树的形式(jdk1.8中增加了红黑树,当链表长度不小于阈值(8)时,将单链表转换为红黑树,这样大大减少了查找时间。小于8时转回为单链表)

下图很好地展示了HashMap的数据结构,的形式分为单链表和红黑树两种结构。

《【Java集合类】HashMap源码分析(jdk1.8)》

——>接着,我们看看每种结构对应的具体实现:

单链表

/**
     * 单链表中的每个节点
     */
    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);
        }
        。。。。
}

由于红黑树涉及到的问题比较多(节点的数据结构,如何插入节点,如何删除节点),不在此详细阐述,可以参考如下资料:

本质上,红黑树就是一颗2-3-4数(B树的一种),插入、删除节点时以2-3-4树的方式考虑就简单多了。

数组(哈希表)

/**
     * The table, initialized on first use, and resized as
     * necessary. When allocated, length is always a power of two.
     * (We also tolerate length zero in some operations to allow
     * bootstrapping mechanics that are currently not needed.)
     */
    transient Node<K,V>[] table;
    /**
     * The number of key-value mappings contained in this map.
     */
    transient int size;

Node[] table,即哈希桶数组。但是要注意数组的大小:

static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
static final int MAXIMUM_CAPACITY = 1 << 30;

并且数组的大小(size)只能是2的幂次方。

——>为什么容量只能是2次幂的形式?

当我们想要找到元素在表中的位置时,需要先对hash值取余数,即hash%n,n代表table的capacity。

源码中通过**(n-1)&hash**的方式,因为&运算的效率高于%运算。

这样数组的长度就必须是2的幕次方,才能等价于hash%n。

初始化

即构造函数,主要需要明确容量和加载因子

  • 阈值 = 容量 * 加载因子
  • loadFactor = capacity * loadFactor

最主要的构造函数:

/**
     * Constructs an empty <tt>HashMap</tt> with the specified initial
     * capacity and load factor.
     *
     * @param  initialCapacity the initial capacity
     * @param  loadFactor      the load factor
     * @throws IllegalArgumentException if the initial capacity is negative
     *         or the load factor is nonpositive
     */
    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;
        //tableSizeFor()方法是将容量转化为大于其容量的最小2次幂形式
        //注意,初始化时直接将容量赋值到阈值:table的初始化被推迟到了put方法中,
        //在put方法中会对threshold重新计算,put方法后面具体分析
        this.threshold = tableSizeFor(initialCapacity);
    }

我们在看看tableSizeFor(initialCapacity)方法:将容量转化为大于等于其容量的最小2次幂形式。

/**
     * 找到大于等于initialCapacity的最小的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;
    }

原理具体分析见:HashMap源码注解 之 静态工具方法hash()、tableSizeFor()(四)

扩容

在每次插入元素的时候都需要检查下map的容量,若小于阈值,则需要扩容。

扩容函数 resize()会遇到三种情况:

  • table已初始化有元素——>扩容2倍,更新阈值,复制元素到新table
  • table未初始化,但是阈值已确定(有参构造器)——>容量等于阈值,再更新阈值
  • table未初始化,阈值也未确定(无参构造器)——>初始容量默认16,更新阈值

注意,在将所有元素复制到新的table(新的capacity)时,不需要像JDK1.7的实现那样重新计算hash,只需要看看原来的hash值新增的那个bit是1还是0就好了,是0的话索引没变,是1的话索引变成“原索引+oldCap”

——>具体源码:

//大前提:capacity都是2次幂形式,扩容到两倍
    //(1)table已有元素
    //(2)table未初始化,但是阈值已确定
    //(3)若table未初始化,阈值也未确定
    //————>最终得到:扩容/或默认容量,初始化table,更新阈值
    final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        //(1)table已有元素——>新容量和阈值扩大到2倍
        if (oldCap > 0) {
            //若旧容量超过最大值
            if (oldCap >= MAXIMUM_CAPACITY) {
                //阈值设置最大值
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            //若旧容量超过16,但新容量(扩大到2倍)小于最大值
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                //阈值扩大到2倍
                newThr = oldThr << 1; // double threshold
        }

        //(2)若table未初始化,但是阈值已确定——>新容量等于构造时的阈值——>
        //调整新阈值threshold = capacity * loadFactor——>初始化table,但size为0
        //(这种情况出现在:在构造函数中已确定了阈值,在putVal函数(put()插入一个元素、putMapEntries()插入map集等会调用putVal)
        //插入元素时调用resize扩容函数)
        else if (oldThr > 0) // initial capacity was placed in threshold
            /**
             * 为什么newCap直接等于oldThr,而不是oldThr/loadFactor?
             *
             * 虽然规定threshold = capacity * loadFactor
             * 但在构造函数中直接赋值threshold = capacity
             * 所以newCap无需调整
             * 
             */
            newCap = oldThr;

        //(3)若table未初始化,阈值也未确定——>初始新容量和阈值——>初始化table,但size为0
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            //注意这里的threshold = capacity * loadFactor
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }

        //情况(2)中,将旧阈值threshold = capacity调整新阈值threshold = capacity * loadFactor
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        //更新阈值
        threshold = newThr;
        
        //初始化table
        @SuppressWarnings({"rawtypes","unchecked"})
            Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;

        //更新元素到新table
        if (oldTab != null) {
            //遍历旧table
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                //遍历桶位中的每个元素
                //首先检查桶中第一个元素
                if ((e = oldTab[j]) != null) {
                    //gc
                    oldTab[j] = null;
                    //①如果桶中只有一个元素
                    if (e.next == null)
                        //新table的位置
                        newTab[e.hash & (newCap - 1)] = e;
                    //②如果桶中不止一个元素,且桶是红黑树的形式
                    else if (e instanceof TreeNode)
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    //③如果桶中不止一个元素,且桶是单链表的形式
                    else { // preserve order
                        //声明了队尾和队头指针。新索引标识(原索引+oldCap)为hi,原索引标识为lo
                        Node<K,V> loHead = null, loTail = null;
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        do {
                            next = e.next;
                            //只需要看看原来的hash值新增的那个bit是1还是0就好了,
                            //是0的话索引没变,是1的话索引变成“原索引+oldCap”
                            //不需要对每个元素重新计算hash值
                            //
                            // 原索引
                            if ((e.hash & oldCap) == 0) {
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            // 原索引+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;
    }

查找操作

1、通过key查找元素:

  • public V get(Object key)

  • public boolean containsKey(Object key)

  • @Override public boolean replace(K key, V oldValue, V newValue)

  • 。。。。

最终源码都会调用getNode()方法,通过元素的hash值找到桶的位置后,再检查桶(单链表或红黑树)中是否有元素。

final Node<K,V> getNode(int hash, Object key) {

        Node<K,V>[] tab; 
        Node<K,V> first, e; 
        int n; K k;
        
        //①table已经初始化,②且长度大于0,③根据hash寻找到的table中桶也不为空
        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的哈希值相同且节点key相同
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

2、通过value查找元素:

public boolean containsValue(Object value) {
        Node<K,V>[] tab; V v;
        if ((tab = table) != null && size > 0) {
            //遍历
            for (int i = 0; i < tab.length; ++i) {
                for (Node<K,V> e = tab[i]; e != null; e = e.next) {
                    if ((v = e.value) == value ||
                        (value != null && value.equals(v)))
                        return true;
                }
            }
        }
        return false;
    }

插入操作

插入过程参见下图:
《【Java集合类】HashMap源码分析(jdk1.8)》

1、插入单个元素:

// 第三个参数 onlyIfAbsent 如果是 true,那么不能覆盖value(除非value为空)
    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未初始化,或长度为0,则先扩容
        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 {
            
            //e为搜索到的节点
            Node<K,V> e; K k;

            //先查找桶中第一个节点
            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) {
                    //(尾插法)如果未找到相同节点,即e=null,在最后插入
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        //如果节点超过8,转化成红黑树形式
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    //如果找到相同节点,保存到e
                    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();
        //LinkedHashMap中被覆盖的afterNodeInsertion方法,用来回调移除最早放入Map的对象
        afterNodeInsertion(evict);
        return null;
    }

2、插入元素集合:

final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
        int s = m.size();
        //判断插入集合大小的有效性
        if (s > 0) {
            //如果table未初始化
            if (table == null) { // pre-size
                float ft = ((float)s / loadFactor) + 1.0F;
                int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                         (int)ft : MAXIMUM_CAPACITY);
                if (t > threshold)
                    threshold = tableSizeFor(t);
            }
            //如果table已初始化,但是待插入map的大小直接超过阈值,则需要调整table的大小
            //(注意是大小直接超过阈值,不是table剩余容量)
            else if (s > threshold)
                resize();

            //正式将待插入map一个一个插入
            for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
                K key = e.getKey();
                V value = e.getValue();
                putVal(hash(key), key, value, false, evict);
            }
        }
    }

删除操作

删除单个元素:

final Node<K,V> removeNode(int hash, Object key, Object value,
                               boolean matchValue, boolean movable) {

        //e代表正在搜索的节点,p代表前个节点
        Node<K,V>[] tab; Node<K,V> p; int n, index;
        //table已经初始化,且长度大于0,根据索引找到的桶的位置不为空
        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;
            //桶中第一个节点就是要寻找的节点
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                node = p;
            //搜索桶中剩余的节点
            else if ((e = p.next) != null) {
                //桶为红黑树的形式
                if (p instanceof TreeNode)
                    node = ((TreeNode<K,V>)p).getTreeNode(hash, 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);
                }
            }
            //移除找到的节点
            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;
                //单链表中有多个节点
                else
                    p.next = node.next;
                ++modCount;
                --size;
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }

参考:

    原文作者:java集合源码分析
    原文地址: https://blog.csdn.net/u013480581/article/details/82056003
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞