HashMap源码解析(JDK1.8)

HashMap源码解析(JDK1.8)

HashMap是一个数组+链表(或者红黑树)实现的散列表,这里注意是JDK1.8之后,JDK1.8之前是数组+链表实现的

同样我们还是先上类的关系图

HashMap类的关系图

从类的关系图中可以看出LinkedList继承一个抽象类和实现了三个接口,然后分别简单介绍一下:

  • AbstractMap:这里主要提供iterator迭代器的相关操作
  • Map:提供散列表的增删改查、迭代器遍历等操作
  • Cloneable:按字段复制操作
  • Serializable:启用其序列化功能操作

属性



    /**
     * The default initial capacity - MUST be a power of two.
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    /**
     * The maximum capacity, used if a higher value is implicitly specified
     * by either of the constructors with arguments.
     * MUST be a power of two <= 1<<30.
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;

    /**
     * The load factor used when none specified in constructor.
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    /**
     * The bin count threshold for using a tree rather than list for a
     * bin.  Bins are converted to trees when adding an element to a
     * bin with at least this many nodes. The value must be greater
     * than 2 and should be at least 8 to mesh with assumptions in
     * tree removal about conversion back to plain bins upon
     * shrinkage.
     */
    static final int TREEIFY_THRESHOLD = 8;

    /**
     * The bin count threshold for untreeifying a (split) bin during a
     * resize operation. Should be less than TREEIFY_THRESHOLD, and at
     * most 6 to mesh with shrinkage detection under removal.
     */
    static final int UNTREEIFY_THRESHOLD = 6;

    /**
     * The smallest table capacity for which bins may be treeified.
     * (Otherwise the table is resized if too many nodes in a bin.)
     * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
     * between resizing and treeification thresholds.
     */
    static final int MIN_TREEIFY_CAPACITY = 64;
    
复制代码

static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;//默认初始容量16,二进制1左移4位,就是4个2相乘

static final int MAXIMUM_CAPACITY = 1 << 30;//最大容量,二进制1左移30位

static final float DEFAULT_LOAD_FACTOR = 0.75f;//构造函数中未指定时使用的负载因子

static final int TREEIFY_THRESHOLD = 8;//使用树而不是列表的箱子计数阈值8,如果链表长度 > 8,则将链表转换为红黑树

static final int UNTREEIFY_THRESHOLD = 6;//使用列表而不是树的箱子计数阈值6,如果红黑树内的数量 < 6时,则红黑树转换为链表

static final int MIN_TREEIFY_CAPACITY = 64;//使用最小树形化容量阈值64,如果当哈希表中的容量 >
64时,才允许树形化链表(即将链表转换成红黑树),否则,若桶内元素太多时,则直接扩容,而不是树形化

构造方法


    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);
    }

    /**
     * Constructs an empty <tt>HashMap</tt> with the specified initial
     * capacity and the default load factor (0.75).
     *
     * @param  initialCapacity the initial capacity.
     * @throws IllegalArgumentException if the initial capacity is negative.
     */
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    /**
     * Constructs an empty <tt>HashMap</tt> with the default initial capacity
     * (16) and the default load factor (0.75).
     */
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

    /**
     * Constructs a new <tt>HashMap</tt> with the same mappings as the
     * specified <tt>Map</tt>.  The <tt>HashMap</tt> is created with
     * default load factor (0.75) and an initial capacity sufficient to
     * hold the mappings in the specified <tt>Map</tt>.
     *
     * @param   m the map whose mappings are to be placed in this map
     * @throws  NullPointerException if the specified map is null
     */
    public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }

复制代码

从四个构造方法中可以看出主要是initialCapacity、loadFactor、threshold这三个的不同参数。还有一个特殊的m直接传数据的构造方法,我们来一一接下来参数的神秘面纱:

initialCapacity:初始容量,默认值采用的是16,JDK1.8之后HashMap虽然采用来数组+链表(或者红黑树)实现的,但是整个开始还是从数组开始的,我们知道数组是有一个初始化容量的,当存储的数据越来越多的时候,我们就必须要进行扩容操作。而为了避免不必要的扩容操作,提升效率,选择一个合适的初始容量就是重中之重。

loadFactor:负载因子,默认值采用的是0.75,当负载因子较大时,去给table数组扩容的可能性就会少,所以相对占用内存较少(空间上较少),但是每条entry链上的元素会相对较多,查询的时间也会增长(时间上较多)。反之就是,负载因子较少的时候,给table数组扩容的可能性就高,那么内存空间占用就多,但是entry链上的元素就会相对较少,查出的时间也会减少。所以才有了负载因子是时间和空间上的一种折中的说法。所以设置负载因子的时候要考虑自己追求的是时间还是空间上的少。

  • threshold:HashMap所能容纳的最大数据量的Node(键值对)个数。threshold = length * loadfactor。也就是说,在数组定义好长度之后,负载因子越大,所能容纳的键值对个数越多。

Float.isNaN()方法分析


    public static boolean isNaN(float v) {
        return (v != v);
    }

复制代码

如果指定的数v不是数字(NAN=Not a Number,即不是一个数字)的值方法返回true,否则返回false。该参数v是要测试的值。

tableSizeFor方法分析


    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;
    }

复制代码

n转化为二进制做右移动多少位,然后再和之前的n做或运算,一直到右移16位做完或运算,然后做了两个三元运算符的计算,(n < 0) ? 1 : (n >= MAXIMUM_CAPACITY)判断得到的值再做value?
MAXIMUM_CAPACITY : n + 1运算,其实就是找到大于或等于cap的最小2的幂。构造方法及其相关的分析好了,现在正式进入HashMap的增删改查源码分析中

增删改查

HashMap中的节点

HashMap中的节点对象是一个存储hash值,key,value以及下一个节点

    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;
        }
    }
复制代码

插入元素/更新元素

HashMap中,put方法的逻辑是最复杂的,我们来一步一步揭开神秘面纱


    public V put(K key, V value) {
        //hash方法下面分析
        return putVal(hash(key), key, value, false, true);
    }

    //真正的方法是putVal
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        //tab如果没有初始化,则进行tab数组的初始化,并赋值初始容量,计算阈值,resize这个方法在下面我们也会来分析一下的
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //如果下标i(i是通过hash值计算得到的)位置的节点为空,则直接在i位置设置相关的节点    
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            //如果通过hash找到的位置有数据,则发生了hash碰撞
            Node<K,V> e; K k;
            //节点key存在,直接覆盖value值
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            //如果是红黑树,则调用红黑树的putTreeVal设置值
            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);
                        //链表长度大于8转换为红黑树进行处理
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    //key已经存在直接覆盖value,跳出循环
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            //经过上面的循环后,如果e不为空,则说明上面插入的值已经存在于当前的hashMap中,那么更新指定位置的键值对
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        //HashMap的size大于阀值,则进去扩容
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

复制代码

总结一下put方法,先根据key得到hash值,然后找到对应的index下标,再判断index下标是否有值,没有值直接插入,如果有值再判断是否有key、hash都一样的,这样的就直接更新值;或者不是再判断是链表或者是红黑树,如果是链表然后对应找是否有对应的节点存在,存在更新值,不存在就拆入节点;如果是红黑树,通过一系列的判断是更新还是新增,这样不做介绍了

hash方法

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

key不为null时,取key的hashCode()与h的右移16位做异或运算,右移16位也就是取了int类型的一般,这样能保证结果均匀分布

resize()方法


    final Node<K,V>[] resize() {
        //拿到老的tab数据
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        //老的阀值
        int oldThr = threshold;
        //新的容量及其阀值
        int newCap, newThr = 0;
        //tab容量大于0
        if (oldCap > 0) {
            //tab容量大于最大容量,不再扩容,直接设置为Interger类型的最大值
            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
        }
        //老阀值大于0,直接用老阀值的值赋值给新的容量
        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) {
            //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;
        
        //如果之前的数组桶里面已经存在数据,由于table容量发生变化,hash值也会发生变化,需要重新计算下标
        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;
    }

复制代码

总结一下:table是否初始化,如果没有初始化就调用无参构造方法,设置默认值;如果以及初始化就进行二倍扩容。
扩容后创建新的table,需要对所有数据进行遍历,如果计算的位置数据为空,直接插入;如果计算的位置为链表,则通过hash算法重新计算下标,然后对链表进行分组;如果是红黑树,则需要进行拆分操作。

删除元素


    public V remove(Object key) {
        Node<K,V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
            null : e.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;
        //根据key和key的hash值,找到相对应的元素
        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;
    }


复制代码

查找元素


    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;
        //判断tab不为null,且tab长度大于0,first节点不为null才能取对应的节点
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            //判断first节点的hash和目标的hash是否一致,并且key不为null且和first.key相等就取得是第一个first节点数据
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            //得到e,e的初始值为first的next,接下来都是e=e.next,只要不为null,就进行判断取值    
            if ((e = first.next) != null) {
                //如果是红黑树,则通过取红黑树的TreeNode取到对应的节点
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                do {
                    //判断hash、key都一致则返回e节点,跳出循环
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

复制代码

其他方法

像containsKey()、clear()这几个我们也来简单的看一下

    //containsKey就是getNode判断节点是否为null
    public boolean containsKey(Object key) {
        return getNode(hash(key), key) != null;
    }

    //循环设置i位置的元素为null
    public void clear() {
        Node<K,V>[] tab;
        modCount++;
        if ((tab = table) != null && size > 0) {
            size = 0;
            for (int i = 0; i < tab.length; ++i)
                tab[i] = null;
        }
    }
    
复制代码

线程安全问题

  • HashMap是线程不安全的
  • HashTable是线程安全的
  • Collections.synchronizedMap()可实现HashMap的线程安全
  • ConcurrentHashMap是线程安全的

相关对比

Java自带的HashMap、HashTable、ConcurrentHashMap、LinkedHashMap、TreeMap之间的对比,还有HashMap和Android独有的SparseArray、ArrayMap的对比

LinkedHashMap:LRU Cache就是通过LinkedHashMap去简单扩展实现的

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享