解读HashMap源码

源码版本为JDK1.8

首先看无参构造方法

    /**
     * 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
    }

使用默认的初始容量(16)和默认的加载因子(0.75)构造一个空的 HashMap

也就是设置链表数组 table 的初始长度为16 到长度16*0.75(12)的时候进行扩容

    /**
     * The table, initialized on first use, and resized as
     * necessary. When allocated, length is always a power of two.
     * (We also tolerate length zero in some operations to allow
     * bootstrapping mechanics that are currently not needed.)
     */
    transient Node<K,V>[] table;

接下来解读put方法

调用hash方法得到一个hash值,再调用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得到hashCode值,用hashCode右移16位后再与原hashCode进行异或得到随机0-15的值(比radom方法效率更高)

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

核心put方法因为里面涉及到的太多,直接以注释方式解读

    /**
     * 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) {
        //定义链表数组、(进行一系列操作的)链表、数组长度、操作的数组下标
        HashMap.Node<K,V>[] tab; HashMap.Node<K,V> p; int n, i;
        //如果内置链表数组为空  或者  刚自定义的链表数组长度为0(也就是说如果还没有进行过数据操作)
        if ((tab = table) == null || (n = tab.length) == 0)
            //则初始化一个链表数组
            n = (tab = resize()).length;
        //如果随机一个数组下标位为空
        if ((p = tab[i = (n - 1) & hash]) == null)
            //则生成一个链表,将数据put到这个位置
            tab[i] = newNode(hash, key, value, null);
        else {
            //或者==>>也就是说  当前数组下标位置已经存在了数据
            //则再定义一个(如果key值重复的已存在)链表、当前位置已存在数据的key
            HashMap.Node<K,V> e; K k;
            //如果两个hash值相等且(key内存地址相同 或者 非空情况下key值相同)
            if (p.hash == hash &&
                    ((k = p.key) == key || (key != null && key.equals(k))))
                //则将该位置链表标记出来进行后续操作
                e = p;
            //如果当前位置下的链表是红黑树,则在红黑树下进行数据对比(如果key相同则标记出来)
            else if (p instanceof HashMap.TreeNode)
                e = ((HashMap.TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                //如果第一位不相同 且 不是红黑树 则将链表进行遍历
                for (int binCount = 0; ; ++binCount) {
                    //如果到了链表的最后都没有相同的key(这时候e也为空了)
                    if ((e = p.next) == null) {
                        //则在链表最后位将数据插入
                        p.next = newNode(hash, key, value, null);
                        //如果链表长度到了8位(0-7)
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            //该方法中还判断了table长度是否小于64,
                            // 如果小于64则采用扩容的方式,否则才转为红黑树
                            treeifyBin(tab, hash);
                        break;
                    }
                    //如果有key值相同 则跳出循环
                    if (e.hash == hash &&
                            ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            //如果以上操作中有相同的key
            if (e != null) { // existing mapping for key
                //将原key对应的值拿出来
                V oldValue = e.value;
                //如果可以进行数据修改 或者 原来的值为空
                if (!onlyIfAbsent || oldValue == null)
                    //则新值替换旧值
                    e.value = value;
                afterNodeAccess(e);
                //返回旧值
                return oldValue;
            }
        }
        //这个字段用做hashMap进行数据时判断是否有其他线程操作过,
        //如果modCount被修改过,则会抛出异常
        ++modCount;
        //如果是添加了新数据(没有重复的数据),则将已保存的数据数量自增
        //该值如果大于阈值,则将数组进行扩容
        // (不管是初始化还是扩容都是2的幂次,所以原map中的数据在扩容后是在原地址或者偏移2的幂次)
        //用大白话说,就是要么原地不动,要么在原数组下标+扩容长度(扩容长度=原长度)的下标处
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

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

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值