HashMap 1.8

1、构造器

  构造器一共有四个可以分为两类:1、传值 2、不传值。一般使用不传值的构造器,不传值的构造器只初始化了loadFactory和threshold两个参数,创建数组是在第一次put的时候创建。构造器的入参名称是initialCapacity但实际上要计算出大于等于initialCapacity的2的幂次方的值作为threshold去设置HashMap,不太理解为什么要这么绕一下起参数名字,一开始就叫threshold不更好?

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

2、put

  老大难的put方法,底层调用的是putVal方法。极简主义的编码风格让这段代码看起来晦涩且又长又硬。

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
Node
<K,V>[] tab; Node<K,V> p; int n, i; (1)
if ((tab = table) == null || (n = tab.length) == 0) (2) 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); 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; }

  (1):声明了一些变量为了后续使用,包括代表数组的tab,新插入节点p,以及两个整形变量n i

  (2):懒加载机制,不传值的构造器新建HashMap的时候没有创建数组,需要在第一次使用的时候初始化数组

2.1 第一次使用初始化数组  

        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;

    当tab为null或者tab的长度为0的时候,需要调用resize方法,resize方法既可以用来初始化一个空的数组也可以用在扩容,这里resize被用来扩容,扩容完毕后n的值为新数组的长度。这里用了两个条件判断是否需要扩容,table==null很好理解,为什么还要tab.length==0呢?

    final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
    
      (1)
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; }

   首先判断resize是用来扩容还是初始化数组,这正是代码块(1)所做的事情,根据此时HashMap的table属性是否为null决定oldCap是否为0,当oldCap为0的时候执行初始化数组操作。其实一个HashMap只有threshold一个属性并没有保存Capacity,newCap只是用于创建数组是规定大小。所以剩下的代码只是根据不同的构造函数设置的不同的属性去建立数组,最终数组的大小是newCap且HashMap的threshold为newThr。

  回到一开始那个让我别扭的地方,新的HashMap的threshold会被用来在第一次新建数组。  

2.2 没有发生哈希冲突

  没有发生哈希冲突直接简单把新Node放到table[i]处。

        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);

2.3 发生了哈希冲突

  在上一步的if判断中,p指向了table[i]处的节点,在这里又声明了一个e引用。

  如果待插入的节点和p指向的节点相同,那么就让e指向p。  

  如果不相同且p指向的table[i]是树节点,那么就执行插入树节点的方法putTreeVal,并让e指向该方法的返回值。

  如果上述都不满足就说明p节点是一个普通的节点,那么和1.7中的思路类似,遍历链表上的节点并找到合适的插入位置,在这一步骤中并没有给引用e赋值。

  执行完上述三步后,如果e!=null说明此时存在了一个和待插入节点完全相同的节点,处理逻辑也和1.7相同,用新的值覆盖旧的值并返回旧的值。

猜你喜欢

转载自www.cnblogs.com/AshOfTime/p/10622897.html