技术头条
首发于技术头条

深入浅出HashMap

定义:

基于哈希表的 Map 接口的实现。此实现提供所有可选的映射操作,并允许使用 null 值和 null 键。它不保证映射的顺序,特别是它不保证该顺序恒久不变。 此实现假定哈希函数将元素适当地分布在各桶之间,可为基本操作(get 和 put)提供稳定的性能。迭代 collection 视图所需的时间与 HashMap 实例的“容量”(桶的数量)及其大小(键-值映射关系数)成比例。所以,如果迭代性能很重要,则不要将初始容量设置得太高(或将加载因子设置得太低)。OK,基础知识就介绍到这,那么让我们看看它的类层次结构和数据结构(图片摘自网络)


了解到这,我们大概知道了它是什么东西,接下来,我们先找到HashMap的构造方法HashMap(int initialCapacity, float loadFactor)

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

上述构造调用了tableSizeFor(initialCapacity),而它也是这个构造方法的灵魂,让我们一起分析它的灵魂

/**
     * 返回一个大于cap的最小整数,这个整数还必须是2的x次幂
     */
    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;
    }

| 即为或操作符,>>>y为无符号右移y位,空位补0,n |= n >>> y会导致它的高n+1位全为1,最终n将为111111..1 加1,即为100000..00,即2的整次幂.

那么问题来了,cap为什么一定要为2的n次幂?

原来,jdk实现中,寻找一个key对应的桶位置是通过 (cap - 1) & hash实现的,当cap为2

的整次幂时, (n - 1) & hash就等同于hash%cap,要知道位运算的效率可是远高于%的,那又有人会问hash是什么呢? 别急,下面让我们甩出hash函数的源码

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

好吧,知道hash是什么了,但为什么要用hash而不是直接hashcode呢?


主要是因为如果直接使用hashcode值,那么这是一个int值(8个16进制数,共32位),int值的范围正负21亿多,但是hash表没有那么长,一般比如初始16,自然散列地址需要对hash表长度取模运算,得到的余数才是地址下标。假设某个key的hashcode是0AAA0000,hash数组长默认16,如果不经过hash函数处理,该键值对会被存放在hash数组中下标为0处,因为0AAA0000 &amp; (16-1) = 0。过了一会儿又存储另外一个键值对,其key的hashcode是0BBB0000,得到数组下标依然是0,这就说明这是个实现得很差的hash算法,因为hashcode的1位全集中在前16位了,导致算出来的数组下标一直是0。于是明明key相差很大的键值对,却存放在了同一个链表里,导致以后查询起来比较慢(蜕化为了顺序查找)。故JDK的设计者使用hash函数的若干次的移位、异或操作,把hashcode的“1位”变得“松散”,非常巧妙。


知道它的构造后,我们看看它的组成,从上图看出,它由一堆桶构成,桶中存放链表,当链表长度大于8时,转换为红黑树(TreeNode),所以我们了解了解链表和TreeNode的数据结构

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


关于TreeNode祥讲,可以参考我的 TreeNode深入学习

/**
     * Implements Map.put and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent 如果对应的entry存在value(value!=null),是否 不 覆盖  true 不覆盖,false:覆盖
     * @param evict if false, the table is in creation mode.
     * @return previous value, or null if none
     */
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
        Node<K,V>[] tab;  Node<K,V> p;
        int n, i;//i为entry对应的数组索引,n为cap
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;//如果table为空,则初始化
        if ((p = tab[i = (n - 1) & hash]) == null)//如果p(table[i])为空,new 一个Node,赋值给table[i]
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;//e最终为和key-value对应的Node
            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;
    }

方法总结:

sorry,总结部分描述不准确,寻找对应的键值对是通过比较key,而不是键值对(稍后会修改)

介绍完put,让我们一起看看删除操作


remove(Object)

/**
 * return:如果与key关联的value为null或者map中不存在与key对应的Node,返回null,否则返回oldValue
 */
public V remove(Object key) {
    Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}

remove()

@Override
    public boolean remove(Object key, Object value) {
        return removeNode(hash(key), key, value, true, true) != null;
    }

他们都调用了removeNode(),唯一不同是前者只需要存在对应的key就删除,后者需要同时存在对应的key-value.那么让我们瞧瞧removeNode的源码

removeNode()

/**
     * Implements Map.remove and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to match if matchValue, else ignored
     * @param matchValue true:必须存在对应的key-value才执行删除操作,false:找到对应的key,就执行删除操作
     * @param movable if false do not move other nodes while removing
     * @return the node, or null if none
     */
    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;//p为tab[index]中的元素,e==p.next
        if ((tab = table) != null && (n = tab.length) > 0 &&
                (p = tab[index = (n - 1) & hash]) != null) {//节点对应的tab[index]不为空
            Node<K,V> node = null, e; K k; V v;//node:要删除的节点
            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);
                }
            }//运行到这里,待删除节点node已经确定
            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;
            }
        }
        //table[index]==null,返回null
        return null;
    }

方法总结:

sorry,总结部分描述不准确,寻找对应的键值对是通过比较key,而不是键值对
上面方法中出现了resize,这是一个扩容方法,也是HashMap的关键函数之一,下面让我们目睹为快

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

方法总结:

说完put和remove,我们应该介绍get了,

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;
        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 {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

0.判断table[index]的状态,如果为空,直接返回null;如果非空,继续判断

1.判断first是否满足条件,满足则返回first,否则判断first是否属于TreeNode(红黑树)类型,

若是则return getTreeNode(hash, key);否则继续遍历,找到则返回,找不到返回null.

编辑于 2017-10-13

文章被以下专栏收录