HashMap原理分析

HashMap的简介(本文以JDK1.8为例)

HashMap是jdk中util包的一个容器,它以key-value的形式来存储一个映射关系。常见的用法如下:

HashMap hashMap = new HashMap(10);
hashMap.put("key","value1");
String value = hashMap.get("key").toString();
int size = hashMap.size();

System.out.println("key=" + value);
System.out.println("hasmap's size is " + size);

运行结果:

key=value1
hasmap's size is 1

HashMap的源码

我们可以从HashMap的构造方法来分析它的一些原理,构造函数源码如下:

/**
 * 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 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 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;
        this.threshold = tableSizeFor(initialCapacity);
    }

从源码以及它的注释中我们可以知道:

如果调用无参构造函数HashMap(),那么它的初始容量initialCapacity=16,它的默认装载因子loadFactor=0.75,它的最大容量为1<<30,也就是2的30次方。(这里可能有人会疑问:这个装载因子有什么用呢?我们一会儿为大家揭晓)

如果细心的读者可能会发现,在初始化的过程中,HashMap还初始化了一个阈值threshold,那么这个threshold是干嘛的呢?我们来看一下tableSizeFor()方法的代码:

/**
     * Returns a power of two size for the given target capacity.
     */
    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一个自定义的容量时,这个threhold的值是一个大于等于自定义capicity的2的次方数。也就是说,HashMap会根据用户自定义的容量大小进行判断,如果容量为不为2的次方数(奇数),那么会对它的扩容阈值threhold进行优化扩大(这样相应的容量capacity也会进行调整,capacity的调整会在put方法的第一次扩容里进行)。比如,如果new HashMap(3),那么它的threhold=4;如果new HashMap(4),它的threhold=4;如果new HashMap(5),它的threhold=8。

那么它为什么要将threhold的值设置成这样呢?我们通过看对成员变量threhold的注释可以知道:

它是下一次进行resize()扩容的阈值,并且threhold = capicity * loadFactor(这个我们可以在resize()方法里看到)。所以,HashMap实例化的时候,只是对它的装载因子和扩容阈值进行了初始化,并没有对承载它的容器进行初始化。这里也就解释了上边装载因子的问题,装载因子是用来计算扩容的阈值的

接下来,我们来看看put方法中都做了些什么?

public V put(K key, V value) {
	return putVal(hash(key), key, value, false, true);
}

put方法将key和value传给putVal方法,并且还对key进行了hash运算,将结果传递给了putVal方法。putValu方法代码如下:

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

在上边代码中,我们看到了一个新的数据结构-Node,并且用了一个Node类型的数组的tab来装我们要存的value值。这个Node的数据结构代码如下:

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

我们从这个Node的数据结构中可以看出,它是用来存放我们所需要存放的key和value的实体数据结构类,并且这个Node中还有一个Node类型的next,那么它是用来干嘛呢?我们从源码中知道,存放key对应的value的下标是通过key的哈希值与数组长度减1后的值取模运算得到的,所以就有可能,其他的key的哈希值取模后也得到相同的数组下标,此时如果该位置有值,那么就将用来存储value值的Node的next指向当前要存储的key-value。
所以,现在我们可以得到一个结论

  1. HashMap的底层实现基本原理是使用了一个Node类型的数组,而每一个Node元素又是一个单向链表
  2. 第一次存放数据时,那么在调用put方法时,会调用resize()方法进行扩容;在这之前是没有数组和链表的。
  3. 如果是当前需要存放的value的下标没有Node节点,那么就新建一个Node节点;如果有节点,则判断是否也等于当前节点,等于了则覆盖当前节点,不等于则判断当前节点是否是一棵树的结构,按照红黑树的结构进行存放。如果当前下标有值但不等于当前下标节点,那么就在当前链表查找到链表的最后一个节点,在它的下边增加一个新节点。
  4. 当同一个下标下的链表节点数超过了TREEIFY_THRESHOLD(8),当前的链表会变成一个红黑树的结构(因为变成一个红黑树以后,能够提高搜索效率

    红黑树的特点如下:
    (1)每个节点或者是黑色,或者是红色。
    (2)根节点是黑色。
    (3)每个叶子节点(NIL)是黑色。 [注意:这里叶子节点,是指为空(NIL或NULL)的叶子节点!]
    (4)如果一个节点是红色的,则它的子节点必须是黑色的。
    (5)从一个节点到该节点的子孙节点的所有路径上包含相同数目的黑节点。

那么下边我们来看一下resize的源码:

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;
        @SuppressWarnings({"rawtypes","unchecked"})
            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;
                            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;
    }

在resize()的代码中,我们可以知道:

HashMap默认数组初始化大小为16,如果自己设置数字,如果不是2的次幂,它会自动调整成大于这个自己设置数值的2的次幂。

HashMap的总结

  1. HashMap是数组+链表构成的,JDK1.8之后,加入了红黑树.
  2. HashMap默认数组初始化大小为16,如果瞎设置数字,它会自动调整成2的倍数.
  3. HashMap链表在长度为8之后,会自动转换成红黑树,数组扩容之后,会打散红黑树,重新设置.
  4. HashMap扩容变化因子是0.75,也就是数组的3/4被占用之后,开始扩容。
  5. 在第一次调用PUT方法之前,HashMap是没有数组也没有链表的,在每次put元素之后,开始检查(生成)数组和链表.
原文地址:https://www.cnblogs.com/mr-ziyoung/p/13609121.html