【Java】HashMap源码分析

HashMap源码分析

继承和接口

  • 继承
    AbstractMap.java
  • 实现接口
    Map,Cloneable,Serializable

静态变量

  1. 初试容量默认是16 -必须是2的次方
    /** * The default initial capacity - MUST be a power of two. */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
  1. 最大容量
    如果具有参数的任一构造函数隐式指定较高值,则使用最大容量。必须是2的次方,且小于2^30
    /** * 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;
  1. 默认加载因子 0.75
    /** * The load factor used when none specified in constructor. */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
  1. 阈值TREEIFY_THRESHOLD
    当存储的节点数目达到该值时,链表转换为红黑树数据结构。
    /** * 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. */
    static final int TREEIFY_THRESHOLD = 8;
  1. UNTREEIFY_THRESHOLD
    /** * 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;
  1. MIN_TREEIFY_CAPACITY
    当桶中的bin被树化时最小的hash表容量。(如果没有达到这个阈值,即hash表容量小于MIN_TREEIFY_CAPACITY,当桶中bin的数量太多时会执行resize扩容操作)这个MIN_TREEIFY_CAPACITY的值至少是TREEIFY_THRESHOLD的4倍。
    /** * 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. */
    static final int MIN_TREEIFY_CAPACITY = 64;

成员变量

  1. table 数组
    在第一次使用时初始化,动态扩容,长度总是为2的次方。
    /** * 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;
  1. entrySet
    /** * Holds cached entrySet(). Note that AbstractMap fields are used * for keySet() and values(). */
    transient Set<Map.Entry<K,V>> entrySet;
  1. size
    记录Map中节点个数
    /** * The number of key-value mappings contained in this map. */
    transient int size;
  1. modCount
    顾名思义就是修改次数,当HashMap有remove,add等操作时,或者其他方式修改了内部结构时,如rehash,都会有记录次数。 此字段用于在HashMap的fail-fast Collection-views上生成迭代器。
    HashMap 不是线程安全的,因此如果在使用迭代器的过程中有其他线程修改了map,那么将抛出ConcurrentModificationException,这就是所谓fail-fast策略。
    /** * 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;
  1. threshold 临界值
    threshold = capacity * load factor;
    当size达到threshold时,HashMap就会自动扩容(resize)
    /** * The next size value at which to resize (capacity * load factor). * * @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;
  1. loadFactor 加载因子
    在初始化对象时,不指定则默认为0.75f,
    /** * The load factor for the hash table. * * @serial */
    final float loadFactor;

关键方法

1. hashCode()

    public final int hashCode() {
        return Objects.hashCode(key) ^ Objects.hashCode(value);
    }

2. equals()

Objects.equals和Object.equals都是针对地址比较,即判断两个引用对象是不是同一个对象。(String中的equals是重写后的。)

    public final boolean equals(Object o) {
        if (o == this)
            return true;
        // 判断是否为实例对象
        if (o instanceof Map.Entry) {
            Map.Entry<?,?> e = (Map.Entry<?,?>)o;
            if (Objects.equals(key, e.getKey()) &&
                Objects.equals(value, e.getValue()))
                return true;
        }
        return false;
    }
    /*其中Objects.equals*/
    public static boolean equals(Object a, Object b) {
        return (a == b) || (a != null && a.equals(b));
    }
    /*其中Object.equals*/
    public boolean equals(Object obj) {
        return (this == obj);
    }

3. hash()

从方法实现中看出:

  • 键为空时,hash值为0;同时可说明,null只能存放一个。
  • 键非空时,先计算出object.hashCode()的结果h,将h其右移后再与object.hashCode()值异或。
    (>>> : 无符号右移,忽略符号位,空位都以0补齐)
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

4. putMapEntries()

    /** * Implements Map.putAll and Map constructor * * @param m the map * @param evict false when initially constructing this map, else * true (relayed to method afterNodeInsertion). */
    final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
        int s = m.size();
        if (s > 0) {
            if (table == null) { // pre-size
                float ft = ((float)s / loadFactor) + 1.0F;
                int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                         (int)ft : MAXIMUM_CAPACITY);
                if (t > threshold)
                    threshold = tableSizeFor(t);
            }
            else if (s > threshold)
                resize();
            for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
                K key = e.getKey();
                V value = e.getValue();
                putVal(hash(key), key, value, false, evict);
            }
        }
    }

5. get()

根据键(key)获取值
先计算key的hash值,索引到数组的位置,

    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))))
                // 此处的equals比较的是对象的hash值,而不是HashMap中计算出来的hash值
                return first;
            if ((e = first.next) != null) {
                if (first instanceof TreeNode)//判断是否转化为红黑树存储,使用getTreeNode
                    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;
    }

6. put()

  1. 如果table为空,调用resize初始化;
  2. 如果根据hash到的table节点为空,无链表挂载,则初始化链表节点信息;
  3. 如果该键存在,直接替换value;不存在,则判断是否为红黑树结构,插入红黑树节点
  4. 如果是链表结构,插入节点,判断是否需要转成红黑树;
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
	// put的具体实现
    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)
            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);
            else {
            	// 这时候就是链表结构了,要把待插入元素挂在链尾
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        // 由于初始即为p.next,所以当插入第9个元素才会树化
                        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;
                }
            }
            // 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;
    }

7. resize()

  1. HashMap中的table不为空:
    容量已经达到最大值,resize扩容失败;
    容量增加为原来2倍,依然未到最大值,同时原来的容量大于默认初试容量,threshold也扩大为2倍。
  2. table为空,初始化了threshold,则新容量赋值为threshold的值。
  3. 默认为空时,即第一次初始化,赋值默认的容量capcitty和threshold
  4. 申请扩容后的新的数组table,如果HashMap不为空,则复制原来的节点到现在的table中,同时清除Old table的引用,以便GC回收。
    在复制的过程中,因为每个table位是链表,重新计算hash,是否位置发生变化,实质只将引用知道头节点即可;
    如果红黑树结构存储,要做一个split操作,因为threshold也扩大了,此时数量可能小于threshold,需要转换为链表结构。
    /** * Initializes or doubles table size. If null, allocates in * accord with initial capacity target held in field threshold. * Otherwise, because we are using power-of-two expansion, the * elements from each bin must either stay at same index, or move * with a power of two offset in the new table. * * @return the table */
    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"})
        // 申请扩容后的新的数组table
            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;
    }

KeySet

顾名思义,键key的集合
官方释义:Map中所有key的集合视图
提供的删除操作:Iterator.remove、 Set.remove、 removeAll、retainAll
不支持添加操作:add,addAll

    public Set<K> keySet() {
        Set<K> ks;
        return (ks = keySet) == null ? (keySet = new KeySet()) : ks;
    }

Values

Map中所有value值的视图,操作同KeySet

    public Collection<V> values() {
        Collection<V> vs;
        return (vs = values) == null ? (values = new Values()) : vs;
    }

EntrySet

Map中Entry的集合视图,即所有key-value的集合。
操作同KeySet。

    public Set<Map.Entry<K,V>> entrySet() {
        Set<Map.Entry<K,V>> es;
        return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
    }

使用keySet, valueSet, entrySet,如果对该 set 进行迭代的同时修改了映射(通过迭代器自己的 remove 操作除外),则迭代结果是不确定的。
/**
* Returns a {@link Set} view of the mappings contained in this map.
* The set is backed by the map, so changes to the map are
* reflected in the set, and vice-versa. If the map is modified
* while an iteration over the set is in progress (except through
* the iterator’s own remove operation, or through the
* setValue operation on a map entry returned by the
* iterator) the results of the iteration are undefined. The set
* supports element removal, which removes the corresponding
* mapping from the map, via the Iterator.remove,
* Set.remove, removeAll, retainAll and
* clear operations. It does not support the
* add or addAll operations.
*
* @return a set view of the mappings contained in this map
*/

    原文作者:hf寒沨
    原文地址: https://blog.csdn.net/hc1017/article/details/89587654
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞