HashMap(三)底层源码分析

HashMap核心属性分析

 /**
         * The default initial capacity - MUST be a power of two.
         * 默认散列表数组长度
         */
        static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    /**
     * The maximum capacity, used if a higher value is implicitly specified
     * by either of the constructors with arguments.
     * MUST be a power of two <= 1<<30.
     * 散列表数组长度的最大长度
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;

    /**
     * The load factor used when none specified in constructor.
     * 默认负载因子大小,当你哈希表中的元素超过阈值,触发扩容
     *      阈值threshold=容量capacity*负载因子loadFactor
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    /**
     * The bin count threshold for using a tree rather than list for a
     * bin.  Bins are converted to trees when adding an element to a
     * bin with at least this many nodes. The value must be greater
     * than 2 and should be at least 8 to mesh with assumptions in
     * tree removal about conversion back to plain bins upon
     * shrinkage.
     * 树化阈值,当链表长度达到8,有可能变成红黑树
     */
    static final int TREEIFY_THRESHOLD = 8;

    /**
     * The bin count threshold for untreeifying a (split) bin during a
     * resize operation. Should be less than TREEIFY_THRESHOLD, and at
     * most 6 to mesh with shrinkage detection under removal.
     * 树降级 称为链表阈值
     */
    static final int UNTREEIFY_THRESHOLD = 6;

    /**
     * The smallest table capacity for which bins may be treeified.
     * (Otherwise the table is resized if too many nodes in a bin.)
     * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
     * between resizing and treeification thresholds.
     * 树化的另一个参数,当哈希表种的所有元素个数超过64,才会允许树化
     */
    static final int MIN_TREEIFY_CAPACITY = 64;
/**
     * 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;

    /**
     * Holds cached entrySet(). Note that AbstractMap fields are used
     * for keySet() and values().
     */
    transient Set<Map.Entry<K,V>> entrySet;

    /**
     * The number of key-value mappings contained in this map.
     * 当前哈希表中元素个数
     */
    transient int size;

    /**
     * The number of times this HashMap has been structurally modified
     * Structural modifications are those that change the number of mappings in
     * the HashMap or otherwise modify its internal structure (e.g.,
     * rehash).  This field is used to make iterators on Collection-views of
     * the HashMap fail-fast.  (See ConcurrentModificationException).
     * 当前哈希表结构修改次数
     */
    transient int modCount;

    /**
     * The next size value at which to resize (capacity * load factor).
     *
     * 扩容阈值 当你哈希表中的元素超过阈值,触发扩容
     * threshold=capacity*loadFactor
     * @serial
     */
    // (The javadoc description is true upon serialization.
    // Additionally, if the table array has not been allocated, this
    // field holds the initial array capacity, or zero signifying
    // DEFAULT_INITIAL_CAPACITY.)
    int threshold;

    /**
     * The load factor for the hash table.
     *负载因子
     *
     *
     * @serial
     */
    final float loadFactor;

构造方法

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

/**
 * 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 default initial capacity
 * (16) and the default load factor (0.75).
 */
public HashMap() {
    this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}

/**
 * Constructs a new <tt>HashMap</tt> with the same mappings as the
 * specified <tt>Map</tt>.  The <tt>HashMap</tt> is created with
 * default load factor (0.75) and an initial capacity sufficient to
 * hold the mappings in the specified <tt>Map</tt>.
 *
 * @param   m the map whose mappings are to be placed in this map
 * @throws  NullPointerException if the specified map is null
 */
public HashMap(Map<? extends K, ? extends V> m) {
    this.loadFactor = DEFAULT_LOAD_FACTOR;
    putMapEntries(m, false);
}

put()方法

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

分析一下这个hash(key)

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

其实就是拿到key的哈希值然后进行一个扰乱,也就是拿到哈希值的二次处理,进行一个与哈希值右移16位的异或,让高16位也参与路由运算,使得hash值更加散列,因为结果要按位与上散列表数组的长度-1,但是数组长度一般比较小,所以高十六位也可以参与进来,使得结果更散列,减少hash冲突。

如果传进来key是null,那hash返回0,这个时候按位与上散列表数组的长度-1,得到也是0,所有在这个结点在散列表数组的第0个内存块

putVal()方法

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
    //tab:引用当前hashMap的散列表
    //p: 表示当前散列表的元素
    //n: 表示散列表数组的长度
    //i: 表示路由寻址结果
    Node<K,V>[] tab; Node<K,V> p; int n, i;

    //延迟初始化逻辑,第一次 调用putVaL时会初始化hashMap对象中的最耗费内存的散列表
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;

    //最简单的一种情况,寻址找到的桶位刚好是null,这个时候,直接将当前k-v=>node 扔进去就可以了
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    else {
        //e: 不为null的话,找到了一个与当前要插入的key-value 一致的key的元素
        //k: 表示临时的一个key
        Node<K,V> e; K k;

        //表示桶位中的该元素,与你当前插入的元素的key完全一致,表示后续需要进行替换操作
        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) {
                //条件成立的话,说明迭代到最后一个元素了, 也没找到一个与你要插入的key 一致的node
                if ((e = p.next) == null) {
                    p.next = newNode(hash, key, value, null);

                    //达到标准,树化了
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        treeifyBin(tab, hash);
                    break;
                }
                //条件成立的话,说明找到了相同key的node元素,需要进行替换操作
                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;
}

​ 总结putVal():三种情况

第一种:插入桶位为空,直接插入

第二种:插入链表,插入的值key相同,如果都没有相同,就尾插,但要判读是否达到树化阈值

第三种,树化了,插入有多种情况。

resize()扩容方法

为什么需要扩容?
为了解决哈希冲突导致的链化影响后面查询效率的问题。 扩容会缓解该问题

第一步是计算扩容后的容量和阈值等属性

inal Node<K,V>[] resize() {
    //oldTab:引用扩容前的哈希表
    Node<K,V>[] oldTab = table;
    //oldCap:表示扩容之前table数组的长度
    int oldCap = (oldTab == null) ? 0 : oldTab.length;
    //oldThr:表示扩容之前的扩容阙值,触发本次扩容的阅值
    int oldThr = threshold;
    //newCap: 扩容之后table数组的大小
    //newThr: 扩容之后,下次再次触发扩容的条件
    int newCap, newThr = 0;

    //条件如果成立说明hashMap中的散到 表已经初始化过了,是一次正常扩容
    if (oldCap > 0) {
        //扩容之前的table数组大小已经达到最大阈值后,则不扩容,且设置扩容条件为int 最大值。
        if (oldCap >= MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return oldTab;
        }
        //oldCap左移一位实现 数值翻倍,并且赋值给newCap, newCap 小于数组最大值限制且扩容之前的阀值>=16
        //这种情况下 则下一次扩容的阈值等于当前阈值翻倍
        else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                oldCap >= DEFAULT_INITIAL_CAPACITY)
            newThr = oldThr << 1; // double threshold
    }
    //oldCap == 0,说明hashMap中的散列表是null
    //1.new HashMap( ini tCap, loadFactor ) ;
    //2.new HashMap(initCap) ;
    //3. new HashMap(map); 并且这个map有数据

    else if (oldThr > 0) // initial capacity was placed in threshold
        newCap = oldThr;
    //oldCap==0
    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节
        Node<K,V> e;

        //说明当前桶位中有数据,但是数据具体是单个数据,还是链表还是红黑树并不知道
        if ((e = oldTab[j]) != null) {
            //方便JVM GC时回收内存
            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;
                    //这里的oldCap没有减一
                    //所以一定是16 32 这些 二进制后面几位都是0000
                    //如果按位与后等于0,说明是地位链表 否则是高位链表 妙
                    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;

get()方法

public V get(Object key) {
    Node<K,V> e;
    return (e = getNode(hash(key), key)) == null ? null : e.value;
}

主要看这个getNode()方法,找到要get 的结点

final Node<K,V> getNode(int hash, Object key) {
    //tab: 引用当前hashMap的散列表
    //first:桶位中的头元素
    //e: 临时node元素
    //n: table数组长度
    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) {
        //定位出来的桶位元素即为咱们要get的数据
        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;
}

remove()方法

public V remove(Object key) {
    Node<K,V> e;
    return (e = removeNode(hash(key), key, null, false, true)) == null ?
            null : e.value;
}

主要看这个removeNode()方法,找到删除的结点

final Node<K,V> removeNode(int hash, Object key, Object value,
                           boolean matchValue, boolean movable) {
    //tab: 引用当前hashMap中的散列表
    //p: 当前node元素
    //n: 表示散列表数组长度
    //index: 表示寻址结果
    Node<K,V>[] tab; Node<K,V> p; int n, index;
    if ((tab = table) != null && (n = tab.length) > 0 &&
            (p = tab[index = (n - 1) & hash]) != null) {
        //说明路由的桶位是有数据的,需要进行查找操作,并且删除

        //node:查找到的结果
        //e: 当前Node的 下一个 元素
        Node<K,V> node = null, e; K k; V v;

        //第一种情况:当前桶位中的元素,即为你要删除的元素
        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不为空的话,说明按照key查找到需要删除的数据了
        if (node != null && (!matchValue || (v = node.value) == value ||
                (value != null && value.equals(v)))) {
            //第一种情况: node是树节点,说明需要进行树节点移除操作
            if (node instanceof TreeNode)
                ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
            //第二种情况:桶位元素即为查找结果,则将该元素的下一个元素放至桶位中
            else if (node == p)
                tab[index] = node.next;
            //第三种情况:将当前元素p的下一个元素设置成要删除元素的 下一个元素
            else
                p.next = node.next;
            ++modCount;
            --size;
            afterNodeRemoval(node);
            return node;
        }
    }
    return null;
}

replcae()方法

public boolean replace(K key, V oldValue, V newValue) {
    Node<K,V> e; V v;
    if ((e = getNode(hash(key), key)) != null &&
            ((v = e.value) == oldValue || (v != null && v.equals(oldValue)))) {
        e.value = newValue;
        afterNodeAccess(e);
        return true;
    }
    return false;
}

找到这个结点,如何替换就行啦

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值