HashMap put get 源码解析

我把纯源码放到了随笔: https://www.cnblogs.com/zhangxuezhi/p/11660818.html

public class HashMap<K, V> extends AbstractMap<K, V> implements Map<K, V>, Cloneable, Serializable

先来看put函数的源码:

    /**
     * Associates the specified value with the specified key in this map.
     * If the map previously contained a mapping for the key, the old
     * value is replaced.
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with <tt>key</tt>, or
     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
     *         (A <tt>null</tt> return can also indicate that the map
     *         previously associated <tt>null</tt> with <tt>key</tt>.)
     */
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

该函数做的事情有两件,首先是计算key的hash值,然后调用putVal函数,先来看看hash计算的函数:

/**
     * Computes key.hashCode() and spreads (XORs) higher bits of hash
     * to lower.  Because the table uses power-of-two masking, sets of
     * hashes that vary only in bits above the current mask will
     * always collide. (Among known examples are sets of Float keys
     * holding consecutive whole numbers in small tables.)  So we
     * apply a transform that spreads the impact of higher bits
     * downward. There is a tradeoff between speed, utility, and
     * quality of bit-spreading. Because many common sets of hashes
     * are already reasonably distributed (so don't benefit from
     * spreading), and because we use trees to handle large sets of
     * collisions in bins, we just XOR some shifted bits in the
     * cheapest possible way to reduce systematic lossage, as well as
     * to incorporate impact of the highest bits that would otherwise
     * never be used in index calculations because of table bounds.
     */
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

如果key为null,返回0;

否则,取key的hashCode,高16位不变,然后将其高16位和低16位进行异或运算,用运算后的值替代原始值的低16位。(>>>为无符号右移,即右移时,在左边填充0。所以hashCode值右移16位之后,其左边16位为0,而与0进行异或运算,值不变。)

个人理解:

  这样计算hash,最终计算出来的hash值,其低16位值同时也包含了高16位值的信息。这是因为一般使用hash值来求解数组下标时,一般使用到的是低位数据,很少会用到高位。除非数组的长度很大,达到2^16的时候,才会开始用到高位。因此一般情况下,这样更能充分利用到高位的信息。

  计算数组下标的方法如下:

n = (tab = resize()).length;

 p = tab[i = (n - 1) & hash]

其中,n是容器table的size,而下标,即i,是通过 key的hash值和(n-1)进行&运算得到的。

因此,计算容器下标的方法,就涉及到key的hash值,以及容器本身的大小,

所以在容器的大小不超过2^16的情况下,其hash值因为同时包含了高低位的信息量,该值更能充分利用hashCode的整体信息,从一定程度上减少hash碰撞,计算出来的下标值,也可以减少群集现象。

有个问题,这类求容器下标i的时候,为什么用 & 运算?而不是使用%求余。这个另开一篇随笔来写吧:https://www.cnblogs.com/zhangxuezhi/p/11868058.html

接下来看putVal函数

    /**
     * Implements Map.put and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value
     * @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;
        if ((tab = table) == null || (n = tab.length) == 0)
            //table 为空
            //n被赋值为table的长度
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            //通过key的hash值获取到的下标,找到的桶里面是空的
            //这里隐含的一个步骤是:p被赋值为key对应hash下标存放的node数据,i被赋值为桶下标
            tab[i] = newNode(hash, key, value, null);
        else {
            //table 不为空,桶不为空
            Node<K,V> e; K k;
            if (p.hash == hash &&
                    ((k = p.key) == key || (key != null && key.equals(k))))
                //key重复
                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
                            //链表长度超过8,转化为红黑树
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                            ((k = e.key) == key || (key != null && key.equals(k))))
                        //链表后续的数据中,有key值重复的
                        break;
                    
                    //p指向p.next
                    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;
    }

以上的关键步骤,我都加上了个人的理解,总体步骤如下:

  1. 容器的table为空时,调用resize(),给table分配空间

  2. 通过key的hash值,计算桶下标值i,

  3. 通过i获取容器的桶,

    如果为空,直接new node;

    如果不为空,比较桶顶部元素的key值

      如果key值重复,直接用新的value覆盖旧value,

      如果key不重复,并且节点类型是树节点,则转到树的处理函数

      如果key不重复,并且节点类型是不是树节点,遍历节点链表,

        如果有重复的key值,则用新value替代旧value,

        如果没有重复的key值,在桶尾部添加new node,然后根据桶的大小,如果超出8,则把链表重构成红黑树

看完put函数,接下来get的函数就比较好理解了:

/**
     * Returns the value to which the specified key is mapped,
     * or {@code null} if this map contains no mapping for the key.
     *
     * <p>More formally, if this map contains a mapping from a key
     * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
     * key.equals(k))}, then this method returns {@code v}; otherwise
     * it returns {@code null}.  (There can be at most one such mapping.)
     *
     * <p>A return value of {@code null} does not <i>necessarily</i>
     * indicate that the map contains no mapping for the key; it's also
     * possible that the map explicitly maps the key to {@code null}.
     * The {@link #containsKey containsKey} operation may be used to
     * distinguish these two cases.
     *
     * @see #put(Object, Object)
     */
    public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

    /**
     * Implements Map.get and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @return the node, or null if none
     */
    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;
    }

类似put,也是先计算key的hash值,然后调用其他函数来执行真正的get操作。

get的大概步骤如下:

  当table不为空,并且通过key的hash计算出来的i值,获取到的桶也不为空时,执行以下步骤,否则返回null

  判断桶的首元素,是否跟key相等,相等则返回该数据的value值

  如果key不相等,

    如果桶的数据结构是红黑树,遍历数结构获取数据

    如果桶的数据结构是链表,遍历链表获取数据

注意,无论是get还是put,其key是否相等的判断如下:

 if (e.hash == hash &&

        ((k = e.key) == key || (key != null && key.equals(k))))

  即,key的hash值相等,并且key值本身也要相等。而其中,hash值的计算又依赖于其hashCode函数,因此,如果要自定义HashMap容器的key的对象,则必须要实现该对象的hashCode函数和equals函数,从而定义其相等的判断条件。

原文地址:https://www.cnblogs.com/zhangxuezhi/p/11671649.html