HashMap详解

216 阅读5分钟

概述

HashMap 和 Hashtable 同作为常见的 Map 实现,两者的区别在于 HashMap 支持 key=null、value=null 而 Hashtable 不支持;HashMap 不支持同步而 Hashtable 采用 synchronized 修饰方法。除此之外,两者提供的功能几乎相同。两者都采取 array+list 的方式存储键值对 Entry,array[i]事实上存储了一个 list 的头结点。但是,相对于 Hashtable,HashMap 会在list.size()都达到一定程度之后(默认8并且array.length>=64),将 list 转换成红黑树。

为了方便叙述,本文中 table 指存储 Entry 的数组结构(Entry[] table);bin 指 table[i]及其 list 或红黑树;capacity 指 table.length,也就是 bin 的数量;threshold 指达到再散列的门槛 size(Entry 总数)。

构造方法

HashMap 和 Hashtable 一样,拥有 loadFactor 字段。如果当前 size>threshold,就会进行再散列以降低散列冲突。如果不指定 loadFactor,两者所有的构造方法都会将 loadFacter 设为默认值(0.75f)。不同之处在于,HashMap 中,table 在需要添加元素的时候初始化,Hashtable 则在构造方法时就初始化了。

    // HashMap
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

    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);
        // 只设置了字段值,table并未初始化
        this.loadFactor = loadFactor;
        // 设为不小于initialCapacity的最小2次幂
        this.threshold = tableSizeFor(initialCapacity);
    }

    // Hashtable
    public Hashtable() {
        this(11, 0.75f);
    }

    public Hashtable(int initialCapacity, float loadFactor) {
        // 参数校验
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal Load: "+loadFactor);

        if (initialCapacity==0)
            initialCapacity = 1;
        this.loadFactor = loadFactor;
        // 初始化了table
        table = new Entry<?,?>[initialCapacity];
        threshold = (int)Math.min(initialCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
    }

HashMap 和 Hashtable 也都支持从其他 Map 构造(使用了批量插入方法):

散列方法

注意到 HashMap 设置 threshold 时,调用了 tableSizeFor:

    // 返回不小于cap的最小2次幂
    static final int tableSizeFor(int cap) {
        int n = -1 >>> Integer.numberOfLeadingZeros(cap - 1); // n=不小于cap的最小2次幂-1
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }

与之相比,Hashtable 的 threshold 设置则要简单许多:

    threshold = (int)Math.min(initialCapacity * loadFactor, MAX_ARRAY_SIZE + 1);

为什么 HashMap 要确保 capacity 是 2 的幂次呢?有这么一个公式:

    a % (2^n) = a & (2^n - 1)

一般情况下,我们计算 hash%table.length 来确定存储的 table 下标,就像 Hashtable 一样:

    int index = (hash & 0x7FFFFFFF) % tab.length;

而当 table.length=2 的幂次的时候,我们就可以把 % 运算转换成 & 运算,于是就变成了

    int index = (hash & 0x7FFFFFFF) & (tab.length - 1)

而这,就是 HashMap 的散列方法:

    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);

所以 HashMap 利用 tableSizeFor 方法,保证容量符合 2^n 形式,从而使散列方法从 % 变成了 -与& 运算,效率提升。

put方法

HashMap 除了支持空 key 和空 value 之外,在 bin 使用 list 实现时,put 会在 list 的尾部添加元素,而 Hashtable 则在 list 的头部添加。

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

    // 由于key==null时,返回0,所以HashMap支持key=null
    // Hashtable直接调用key.hashCode(),因此不支持key=null
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        // 利用resize()初始化table
        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);
            // list时
            else {
                // 遍历list
                for (int binCount = 0; ; ++binCount) {
                    // 无散列冲突
                    if ((e = p.next) == null) {
                        // 增加到list末尾
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    // bin中存在重复key,break existing;
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e; // 循环
                }
            }
            // existing:
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                // 钩子方法,详见LinkedHashMap篇
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        // size>threshold则再散列
        if (++size > threshold)
            resize();
        // 钩子方法,详见LinkedHashMap篇
        afterNodeInsertion(evict);
        return null;
    }

    // Hashtable
    public synchronized V put(K key, V value) {
        // Make sure the value is not null
        if (value == null) {
            throw new NullPointerException();
        }

        // Makes sure the key is not already in the hashtable.
        Entry<?,?> tab[] = table;
        int hash = key.hashCode();
        int index = (hash & 0x7FFFFFFF) % tab.length;
        @SuppressWarnings("unchecked")
        Entry<K,V> entry = (Entry<K,V>)tab[index];
        // 遍历,判断元素是否重复
        for(; entry != null ; entry = entry.next) {
            if ((entry.hash == hash) && entry.key.equals(key)) {
                V old = entry.value;
                entry.value = value;
                return old;
            }
        }
        // 增加结点到list头部
        addEntry(hash, key, value, index);
        return null;
    }

get方法

与 hashtable 相比,由于 HashMap 支持 null,所以判断 key 是否相等时,使用(k = first.key) == key || (key != null && key.equals(k)))

    // HashMap
    public V get(Object key) {
        Node<K,V> e;
        // 支持value==null
        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))))  // 支持key=null时
                return first;
            if ((e = first.next) != null) {
                // 红黑树
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                // list
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

    // Hashtable
    public synchronized V get(Object key) {
        Entry<?,?> tab[] = table;
        int hash = key.hashCode();
        // 散列方法没有优化
        int index = (hash & 0x7FFFFFFF) % tab.length;
        for (Entry<?,?> e = tab[index] ; e != null ; e = e.next) {
            // 不存在key=null的情况
            if ((e.hash == hash) && e.key.equals(key)) {
                return (V)e.value;
            }
        }
        return null;
    }

再散列resize

Hashtable 的再散列方法详见 Hashtable 篇。相对于 Hashtable,HashMap 因为对散列方法进行了优化,所以再散列会有这些特性:

  • newCap = oldCap << 1
  • newThr = oldThr << 1

根据以上事实,可以有如下推导:

假设 oldCap=2^n,

当 hash&2^n=0 时,hash<2^n,所以 hash&(2^(n+1)-1)=hash&(2^n-1),即 newIndex=oldIndex

当 hash&2^n!=0 时,hash>=2^n,所以 hash&(2^(n+1)-1)=hash&(2^n-1)+2^n,即 newIndex=oldIndex+oldCap

注意如果结构原来是红黑树,并且再散列之后的树小于6的话,就会恢复成链表。

这是 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);
        }
        // (oldCap<<1)>MAXIMUM_CAPACITY时,不保证table.length是2的幂次
        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;
                    // bin中只有一个元素
                    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
                        // 原table[index]
                        Node<K,V> loHead = null, loTail = null;
                        // 新table[index]
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        // 见上文推导
                        do {
                            next = e.next;
                            if ((e.hash & oldCap) == 0) { // newIndex=oldIndex
                                // 添加到末尾
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            else { // newIndex=oldIndex+oldCap
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        if (loTail != null) { // newIndex=oldIndex
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) { // newIndex=oldIndex+oldCap
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }