HashMap源码分析

  • 概述

HashMap是基于HashTableMap接口的实现。HashMap允许null键和null值,在计算键的Hash值时,null键的hash值为0HashMap 并不保证键值对的顺序,这意味着在进行某些操作后,键值对的顺序可能会发生变化。另外,需要注意的是,HashMap 是非线程安全类,在多线程环境下可能会存在问题。

  • 实现原理

HashMap的底层是基于数组+链表结构来实现的,在Jdk1.8中,对底层结构又进行了优化升级,添加了红黑树结构体。

如上图,这个HashMap对象底层就是由一个数组+链表+红黑树的结构体。为什么要这么做呢?我们数组的特点是寻址容易,插入、删除慢,而链表的特点是寻址慢,但是插入、删除快。而HashMap正式结合了数组和链表各自的优点,提升了HashMap的查询、插入、删除等操作的性能。

查找hash=37的节点。

1、首先我们根据37%16知道37位于第5个桶中,

2、然后从链表的first节点开始遍历,直到找到节点或者到达尾节点为止。

Jdk1.8加入了红黑树的实现,使得在遍历链表节点时速度更快。对于红黑树,我会在具体的一个章节中详细分析。

  • 源码分析

常量

 /**
     * 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.
     */
    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.
     */
    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.
     */
    static final int MIN_TREEIFY_CAPACITY = 64;

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

DEFAULT_INITIAL_CAPACITY

首先当我们通过无参的构造函数new一个hashMap的时候,系统就会帮我们指定你HashMap的默认大小为DEFAULT_INITIAL_CAPACITY,也就是2^{4},当然我们可以刻自己指定初始容量的大小,只不过要注意必须是2^{n}且小于MAXIMUM_CAPACITY。

MAXIMUM_CAPACITY

桶bucket最大的容量MAXIMUM_CAPACITY,其值为2^{30}

DEFAULT_LOAD_FACTOR

加载因子loadFactor的默认值为0.75,当bucket的的填满程度超过了这个loadFactor的比例就会要求对bucket进行扩张。

TREEIFY_THRESHOLD

链表节点转为红黑树的阈值,默认为8个。如果该桶bucket的链表节点数超过了这个阈值,就需要将链表转为红黑树结构。

UNTREEIFY_THRESHOLD

红黑树结构还原为链表的最小值,默认为6个。如果该桶bucket的红黑树节点小于这个阈值,就要求将红黑树结构体转为链表。

MIN_TREEIFY_CAPACITY

转为红黑树的最小bucket容量,默认为64。如果bucket容量为超过MIN_TREEIFY_CAPACITY,程序会优先考虑扩容,而不是优先将链表转为红黑树结构体。

size

size表示当前HashMap中已经储存的Node<key,value>的数量,包括数组和链表中的的Node<key,value>。threshold表示扩容的临界值,如果size大于这个值,则必需调用resize()方法进行扩容。

threshold

阈值,threshold=bucket的容量*loadFactor。当节点数,所有bucket的容量超过了阈值就要求对bucket进扩容。

table[]

这个是HashMap组成元素。是一个Node结构体。

 /**
     * Basic hash bin node, used for most entries.  (See below for
     * TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
     */
    static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;

        Node(int hash, K key, V value, Node<K,V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }

        public final K getKey()        { return key; }
        public final V getValue()      { return value; }
        public final String toString() { return key + "=" + value; }

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

        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

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

Node<K,V>是HashMap的一个内部类,他既是HashMap底层数组的组成元素,又是每个单向链表的组成元素。它其中包含了数组元素所需要的key与value,以及链表所需要的指向下一个节点的引用域next。

构造方法

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

我们看看构造方法1使用tableSizeFor(initialCapacity)来计算bucket容量的阈值。

 /**
     * Returns a power of two size for the given target capacity.
     */
    static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }

该方法是获取小于等于cap的最大2^{n}。在jdk之前的版本使用的是每次扩大2倍再与cap比较获取目标值。而jdk8的方法使用的是将最高位1左移,同时与自己进行|运算来获取目标值。我们看一个实例就大概就明了了这个算法的用意。

假设我们传入的cap=65,那么按计划我们获取的目标值应该是64,也就是2^{6}

1、按方法我们先将65向右移动1位,然后与65进行&运算

高位已经集齐了2位的1。

2、将结果向右移动2位,再进行|运算

高位集齐4位的1

3、将结果向右移动4位,再进行|运算

我们发现这个时候右边集齐了6位数字1,00111111值等于63,然后加1等于64就是我们想要的目标值。即便之后向右移8位,16位,同时|运算还是一样的结果。看到这里觉得神奇吧,二进制移位,|运算确实比原来方法高效。确实比老式的方法每次扩大2倍再比较来得巧妙。其实这里的核心思想无非就是以最高位的1位标杆,右边全部给补上1(最高位的1舍去),最后得到的结果加1就是我们要的目标值。

查找机制

HashMap 的查找操作比较简单,查找步骤与原理篇介绍一致,即先定位键值对所在的桶的位置,然后再对链表或红黑树进行查找。

在分析查找节点的源代码之前,我们先看看获取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);
    }

该方法将自身的hash值右移16位后再与自己hash值进行^运算。这里右移16位是想让高位16位数字也参与到运算,增加计算的复杂度,从而减小节点入桶时发生下标索引的碰撞发生的频率。

获取key入桶的下标索引:Index=(cap - 1) & hash

capHashMap的桶的容量。Jdk旧版本是直接通过hash%cap(取模或者取余数)获取下标索引。Jdk新版本,具体也不知道哪个版本了,将方法进行了升级,直接通过二进制数据的&运算来获取桶的下标索引。要理解这个公式,我们来看一个实例。假设cap=16hash=31

通过公式(16 - 1) & 31计算与31%16计算结果是一致的。由上图我们发现大于hash高位数字都不参与计算,因为cap-1高位的数字都是0,所以hash高位的数字与0进行&运算后都等于0。从这里我也才明白前面取hash值的时候为什么使用hash&hash>>>16算法,就是为了保证hash高位的数字也能参与运算,增加算法复杂度,减少桶下标索引的碰撞。真是不得不佩服作者的逻辑有多缜密。

查询代码如下:

public V get(Object key) {
        Node<K,V> e;
        // hash(key),通过hash方法获取key的hash值,减小节点入桶的碰撞几率
        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;
		//tab不为空,且长度大于0		
        if ((tab = table) != null && (n = tab.length) > 0 &&
            //(n - 1) & hash定位到节点在哪个桶
            (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;
    }

插入节点

1、首先获取桶的位置

2、查询链表或者红黑树是否还有该节点

3、插入节点,调整链表或者红黑树

代码如下:

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


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为空,需要对table进行扩容
            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) {
				//将下一个节点p.next设置为当前节点e
                    if ((e = p.next) == null) {
           /**如果当前节点的下一节点为空,则说明当前节点已经为尾节点,但是我们要的
           key值没有找到,则需要在链表的尾节点添加新的节点。
           p.next = newNode(hash, key, value, null);
           如果新增节点后,该链表的节点超过了转为红黑树的阈值TREEIFY_THRESHOLD,
           我们就需要将其转为红黑树
           */
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
					//找到了匹配的key(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
                V oldValue = e.value;
				//如果onlyIfAbsent==true,则要求需要替换原来的值
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
				//该方法为抽象方法,用户可以灵活使用进行后续操作
                afterNodeAccess(e);
				//返回旧值
                return oldValue;
            }
        }
		//代码走到这里,说明当前要插入的节点不存在于桶中,则需要新增节点
        ++modCount;
		//当前容量超过了阈值,需要对桶容量进行扩容
        if (++size > threshold)
            resize();
		//新增节点后的操作,该方法为抽象方法,用户可以灵活使用进行后续操作
        afterNodeInsertion(evict);
		//因为是新增节点,所以说明旧值未找到,则返回空
        return null;
}

如果当前链表的节点超过了转为红黑树的阈值TREEIFY_THRESHOLD,要需要选择接下来的动作是先扩容还是将链表转为红黑树。

final void treeifyBin(Node<K,V>[] tab, int hash) {
	int n, index; Node<K,V> e;
	/**
     在转为红黑树之前,判断当前tab容量是否超过了阈值
     MIN_TREEIFY_CAPACITY,没有超过则选择对bucket容量进行扩容,超过了
     则将当前桶的链表转为红黑树
    */
	if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
		resize();
	else if ((e = tab[index = (n - 1) & hash]) != null) {
	//声明首节点hd,当前节点tl
		TreeNode<K,V> hd = null, tl = null;
		do {
			//通过普通节点,创建红黑树节点
			TreeNode<K,V> p = replacementTreeNode(e, null);
			if (tl == null)
            //如果当前节点为空,则p为首节点,将hd设置为首节点
				hd = p;
			else {
				p.prev = tl;//下一个节点p的前节点为当前节点tl
				tl.next = p;//将当前节点tl的下一个节点设置为p
			}
			tl = p;//变更当前节点tl为下一个节点p
		} while ((e = e.next) != null);
		//table[index]首节点设置为首节点hd
		if ((tab[index] = hd) != null)
		/**
         上面的步骤只是创建了红黑树节点,然后使用链表方式串联起来,
         接下来这个方法才是将链表真正转为红黑树
        */
			hd.treeify(tab);
	}
}

扩容机制

在 HashMap 中,桶数组的长度均是2的幂,阈值大小为桶数组长度与负载因子的乘积。当 HashMap 中的键值对数量超过阈值时,进行扩容。HashMap的扩容与其他集合的扩容不大一样,HashMap 按当前桶数组长度的2倍进行扩容,阈值也变为原来的2倍(如果计算过程中,阈值溢出归零,则按阈值公式重新计算)。扩容之后,要重新计算键值对的位置,并把它们移动到合适的位置上去。

/**
扩容选择:
case 1:
如果当前容量是否已经初始化,即oldCap>0。
判断当前容量是否已超过了最大阈值MAXIMUM_CAPACITY,超过不再扩容直接返回。
没有超过,将当前容量扩大2倍,同时当前阈值也扩大2倍,当然扩大后的容量还是要
在最大阈值MAXIMUM_CAPACITY范围之内。

case 2:如果当前容量未初始化,当前阈值已经初始化。
将当前容量设置为当前阈值的大小。这个在调用有参数的构造方法的时候会发生。
public HashMap(int initialCapacity, float loadFactor) {...
        this.loadFactor = loadFactor;
        this.threshold = tableSizeFor(initialCapacity);
}


case 3:如果容量和阈值都未初始化,这个在调用无参的构造方法的时候会发生。使用默认的
容量大小和默认的加载因子来设定当前的容量和当前阈值。
public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

执行完以上任何一种情况之后,如果新的阈值未设置(情况3有可能发生),则通过过加载因子和
新的容量来设置。

*/
final Node<K,V>[] resize() {
	Node<K,V>[] oldTab = table;
	//
	int oldCap = (oldTab == null) ? 0 : oldTab.length;
	int oldThr = threshold;//旧的tab阈值
	int newCap, newThr = 0;//新的tab容量,新的阈值
	
	//如果旧的tab容量不为空,表明容量已经初始化过了
	if (oldCap > 0) {
	//当旧的tab容量已经超过最大值,则不再扩容直接返回
		if (oldCap >= MAXIMUM_CAPACITY) {
			threshold = Integer.MAX_VALUE;
			return oldTab;
		}
	//按旧容量和阈值的2倍计算新容量和阈值的大小
		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
	/*
	 * 初始化时,将 threshold 的值赋值给 newCap,
	 * HashMap 使用 threshold 变量暂时保存 initialCapacity 参数的值
	 */ 
		newCap = oldThr;
	else {               // zero initial threshold signifies using defaults
	 /*
	 * 调用无参构造方法时,桶数组tab容量为默认容量,
	 * 阈值为默认容量与默认负载因子乘积
	 */
		newCap = DEFAULT_INITIAL_CAPACITY;
		newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
	}
	//newThr 为 0 时,按阈值计算公式进行计算
	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;//如果原有tab[j]链表不为空,则先将其清空
				if (e.next == null)
				//tab[j]链表的第一个元素的下一个元素为空,则说明该链表只有一个元素
					newTab[e.hash & (newCap - 1)] = e;
				else if (e instanceof TreeNode)
                    //拆分原来的链表
					((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
				else { // preserve order
				/**当前循环的算法,通过解析分析发现,如果(e.hash & oldCap)的值为0时,
                tabl扩张后,e.hash对应的索引是不变的,而e.hash & oldCap的值不等于0时,
                tab扩张后,新的索引=原来的索引+oldCap
                */
					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) {
						//如果(e.hash & oldCap)的值为0,则保持原有的tab[index]不变
							if (loTail == null)
								loHead = e;
							else
								loTail.next = e;
							loTail = e;
						}
						//如果(e.hash & oldCap)的值不为0,则加入到新的tab[index]下
						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;//老的tab,nexIndex=oldIndex
					}
					if (hiTail != null) {
						hiTail.next = null;
						newTab[j + oldCap] = hiHead;//新的tab,newIndex=oldIndex+oldCap
					}
				}
			}
		}
	}
	return newTab;
}

在该方法中使用e.hash & oldCap是否等于0来判断扩容后,原节点的索引位置,是保持原索引位置,还是原索引位置+oldCap。还是习惯使用实例来分析下,假设oldCap=16,对于hash&oldCap

分三种情况分析:

1、hash的值小于16,用二进制表示如下,x可以是1或0

Hash&16:

由上图我们可以得出结论,无论x是1还是0,进行&运算后的值都是0。而且我们知道小于16的数字,对16取模,还是对32取模都是自己hash本身的值。也就是扩容后,索引位置不需要改变。

2、如果hash大于等于16,而且第8位数字为1,我们看看&运算又会发生什么?

由上图我们得出结论,结果值都不可能为0。而且我们知道,在1左边高位的数xxxx xxxx xxxx xxxx xxxx xxxx无论取什么值,对32取模一定等于0。(这个显然的,应该没有疑问吧,因为左边是1xxx xxxx,二进制数,1向左移动1位是扩大两倍)1本身(代表数字1000 0000)对16取模等于0,1右边的数xxx xxxx对16取模等于xxx xxxx,1xxx xxxx对16取模就是xxx xxxx。但是对于32取模呢,因为1(1000 0000)对32取模为16,xxx xxxx对32取模为xxx xxxx,则1xxx xxxx对32取模等于1xxx xxxx,也就是xxx xxxx + 16,也就是原来的hash值xxx xxxx加16。那么扩展后,索引值是原来的索引值加上16。

3、如果hash大于等于16,而且第8位数字为0,我们看看&运算又会发生什么?

由上图我们得出结论,结果值都为0。由上图我们可以知道0左边高位的数xxxx xxxx xxxx xxxx xxxx xxxx对32取模一定是0,而0本身(代表数字0000 0000)对32取模也一定是0。0左边的数xxx xxxx因为小于16,所以对16或者32取模后的值都是xxx xxxx。所以0xxx xxxx对于16或者32取模都是xxx xxxx。

由上面三种情况总结,1和3的结果一致,桶tab扩容后,索引值都是原来的索引值。而情况2,索引值是原来的索引值加上16。那么1和3的共同条件是数字n与16进行&运算结果都为0,情况2则相反不等于0。所以我们得出结论,当hash&oldCap结果等于0时,桶tab扩容2倍后,索引值保持不变,不等于0的时候,桶tab扩容2倍后,索引值等于原来的索引值+oldCap。

删除机制

对于HashMap的删除,普通的链表删除还是比较简单,但是对于红黑树的删除确实一个难点。

 final void removeTreeNode(HashMap<K,V> map, Node<K,V>[] tab,
						  boolean movable) {
	int n;
	if (tab == null || (n = tab.length) == 0)
		return;
	int index = (n - 1) & hash;
	//声明首节点first,根节点root=first,根节点的左孩子rl
	TreeNode<K,V> first = (TreeNode<K,V>)tab[index], root = first, rl;
	//声明succ:删除节点this的下一节点,pred:删除节点p的上一节点
	TreeNode<K,V> succ = (TreeNode<K,V>)next, pred = prev;
	/**
     删除节点this的pred前节点为空,则将首节点设置为删除节点this的
    下一节点succ普通链表节点删除开始,接下来几个步骤为普通连接节点关系的删除
    (因为这个tab链表实际包含了两种结构体:普通链表和红黑树,在这里只是变更了
     普通链表的pred和next的关联关系,并没有变更红黑树parent、right、left的自
     身属性关系,各自关系删除不会影响彼此)
     */
	if (pred == null)
//如果删除节点this的前节点为空,则将首节点设置为删除节点下一个节点succ
		tab[index] = first = succ;
	else
//如果删除节点this的前节点不为空,则将前节点的next指针指向删除节点的下一个节点succ
		pred.next = succ;
	if (succ != null)
//如果删除节点this的下一个节点succ不为空,则将succ的prev指针指向删除节点this的前一个节点pred
		succ.prev = pred;
//普通链表节点删除结束,到此普通链表的前后关联关系已经变更完毕,相比红黑树的删除确实简单
	if (first == null)
		return;//如果首节点为空,则说明该table[index]链表只包含删除的节点this
	
	/**
    接下来应该红黑树关联关系删除,红黑树的删除大致分为四步骤
	1、寻找代替P节点的目标节点,如果有P节点有右子树PR,则目标节点S为PR上最小的节点,
     如果没有右子数,则为P节点左子树上PL上最大的节点
	2、替换节点,将P节点与S节点交换,包括颜色也一起交换
	3、真正删除节点P,调整P节点的辈份关系
	4、调整节点,即调整节点的颜色,保持红黑树的五大性质。
	获取红黑树根节点
    */
	if (root.parent != null)
		root = root.root();
		
	//这里看的不是太明白,估计是指该链表的节点没有超过限制范围,所以将其转换为普通链表
	if (root == null || root.right == null ||
		(rl = root.left) == null || rl.left == null) {
		tab[index] = first.untreeify(map);  // too small
		return;
	}
	
	/**
    声明删除节点p为当前节点,删除节点的左孩子pl,删除节点的右孩子pr,
    替换节点replacement,这里替换节点replacement有必要解释下,首先我们查找到
    目标节点s,会将s节点和p节点交换,包括颜色和位置关系,	交换完之后,p就真正替
    换了s,之后就是真正删除p节点了。删除p节点就是用p节点的孩子替换P,或者将p
    节点至为空。这个孩子节点或者空节点就是所谓的replacement节点。
     */
	TreeNode<K,V> p = this, pl = left, pr = right, replacement;
	
	//如果删除节点p的左孩子pl和右孩子pr都不为空的情况
	if (pl != null && pr != null) {
	
	//声明目标节点s,将s初始化为删除节点p的右孩子pr(如果pr没有左孩子,
    //则s就等于pr),sl:目标节点的左孩子
		TreeNode<K,V> s = pr, sl;
	//获取目标节点s,s为pr子树上的最小节点(如果pr没有左孩子,则s等于pr)
		while ((sl = s.left) != null) // find successor
			s = sl;//s:pr上最小的左孩子节点(前提pr有左孩子)
			
		//将目标节点s和删除节点p的颜色交换
		boolean c = s.red; s.red = p.red; p.red = c; // swap colors
		
		TreeNode<K,V> sr = s.right;//目标节点的右孩子
		TreeNode<K,V> pp = p.parent;//删除节点p的父亲节点
		//删除节点p是目标节点s的直接父亲,(即pr没有左孩子的情况)
		if (s == pr) { // p was s's direct parent
			p.parent = s;
			s.right = p;//刚开始看这个方法的时候,一直疑问S比P大,
        //为什么P会设置成S的右孩子?后来才明白这里只是交换S和P,
		//	交换完后续还会将P节点删除,在这里就是最后S右孩子P会被删除。
		}
		else {
		//声明sp为目标节点s的父亲节点
			TreeNode<K,V> sp = s.parent;
			//交换节点s和节点p的关系,将删除节点p的父亲节点设置为目标节点s的父亲节点
			if ((p.parent = sp) != null) {
				if (s == sp.left)
        //如果目标节点s是sp的左孩子,则将sp的左孩子设置为p
					sp.left = p;
				else
        //如果目标节点s是sp的右孩子(只有一种情况,pr没有左孩子)
					sp.right = p;
			}
			//将s的右孩子设置为pr,即s替换p节点
			if ((s.right = pr) != null)
				pr.parent = s;//pr节点的父亲节点设置为s
		}
		//因为p已经和目标节点s交换,s是最小的左节点,所以s是没有左孩子的,
        //那么交换后,p也是没有左孩子的。
		p.left = null;
		if ((p.right = sr) != null)//p的右孩子设置为s的右孩子sr
			sr.parent = p;		//s的右孩子sr的父亲节点设置为p		
		if ((s.left = pl) != null)//s的左孩子设置为p的左孩子	
			pl.parent = s;//p的左孩子pl的父亲节点设置为s
		if ((s.parent = pp) == null)//目标节点s的父亲节点设置为p的父亲节点pp
			root = s;//如果p的父亲节点pp为空,则将s设置为根节点root
		else if (p == pp.left)//如果p是父亲节点pp的左孩子,则将父亲节点pp的左孩子设置为s
			pp.left = s;
		else
			pp.right = s;//如果p是父亲节点pp的右孩子,则将父亲节点pp的右孩子设置为s
		if (sr != null)//如果s的右孩子不为空,则将replacement设置为sr
			replacement = sr;
		else
			replacement = p;//如果s的右孩子为空,则将replacement设置为p
	}
	//如果删除节点p没有右孩子,那么pl树上最多一个非空节点,
   //而且只能为红色,所以pl(replacement)还是叶子节点
	else if (pl != null)
		replacement = pl;
	//如果删除节点p没有左孩子,那么pr树上最多一个非空节点,而且
    //只能为红色,所以pr(replacement)还是叶子节点
	else if (pr != null)
		replacement = pr;
	else
		replacement = p;
//这里开始,将真正开始删除p节点,即把p节点排除出红黑树的关系(记住这里只是排除红黑树的关系,
 普通链表的关系已经在第一步骤中排除)
//如果交换后的节点p有左孩子或者右孩子的情况
	if (replacement != p) {//替代节点不等于p(原来目标节点s所在的位置),
  //则p节点有左孩子或者右孩子
//将replacement的父亲节点设置为p的父亲节点,即删除了p
		TreeNode<K,V> pp = replacement.parent = p.parent;
		if (pp == null)
	//两种情况:1、当p的pr树只有一个pr节点的时候;
    //2、p只有左节点pl的情况。当然这两种情况前提都是p没父节点
			root = replacement;
		else if (p == pp.left)
//如果删除节点p(主意这里的p已经是交换后的p)是父亲节点的左孩子(原p节点含有右子树pr)
			pp.left = replacement;
		else
//如果删除节点p(主意这里的p已经是交换后的p)是父亲节点的右孩子(原p节点右子树为空)
			pp.right = replacement;
//断绝p的所有红黑树关系,即最终删除了p节点
		p.left = p.right = p.parent = null;、
	}

	//删除完节点后,可能会造成红黑树不满足其固有性质,则需要对其节点进行调整
	//如果删除节点是红色,那么该节点肯定没有孩子节点,则直接删除红色节点,
    //变为NIL节点即可,不需要进入调整方法balanceDeletion
	TreeNode<K,V> r = p.red ? root : balanceDeletion(root, replacement);

	//如果交换后的节点p没有左右孩子,因为p已经是叶子节点,不需要进行删除后的调整。
	if (replacement == p) {  // detach
		TreeNode<K,V> pp = p.parent;
		p.parent = null;
		if (pp != null) {
			if (p == pp.left)
				pp.left = null;
			else if (p == pp.right)
				pp.right = null;
		}
	}
	if (movable)
		moveRootToFront(tab, r);
}

对于HashMap的源码分析到这里,而且在内部还有内部方法没有分析到,特别对于TreeNode内部类类的方法。对于TreeNode类会分一个章节来特别说说,因为TreeNode是红黑树的基本元素。最底层新增、删除都在该类中。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值