HashMap

一. 关于 HashMap 常见的内容:

1. 描述: 实现了 Map<K, V> 接口;元素以键值对的形式存储;key不可重复;keyvalue都可以为null,但是key只能有一个为null;无序存储,不能通过时间或者其他排序方式对其元素进行排序;不是线程安全的集合.
2. 继承以及实现关系:
public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {
}
3. Map<K, V> 接口定义了Map 的方法和一些默认实现, AbstractMap<K,V> 实现了 Map<K,V> 接口,对其中一些方法添加了实现, Cloneable 接口表示可以克隆, Serializable接口表示可以序列化,可以用做数据传输.

二. HashMap 的实现原理:

1. HashMap 是通过数组和链表以及红黑树(后面简称树)来实现的, 每一个键值对都存放在一个实现了 Map.Entity<K, V> 的 Node<K,V> 节点中.
2. HashMap 中维护一个数组,这个数组就是哈希表,数组长度就是哈希表的容量, 哈希表示根据元素的key的哈希值通过算法获得一个不大于数组长度的数字作为元素在数组中位置的下标,每次取元素也是根据哈希值和相同的算法找到相应的下标志,从数组该下标处取.由于使用有限长的哈希值,其表示的内容必然是有限个,而可以存放的内容是无限的,必然会有同一个哈希值对应多个元素,便是hash冲突(后面会有详细解释)
3. 图片演示:

HashMap结构图
以上图片仅为了演示结构和原理,对容量等细节没有考虑和说明

三. HashMap 中定义的常量,属性和节点

1. 常量及描述:
/**
     * The default initial capacity - MUST be a power of two.
     * 默认初始容量 16
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
    /**
     * 最大容量
     * MUST be a power of two <= 1<<30.
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;
    /**
     * 默认加载因子 float型 0.75
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    /**
     * 需要转为树的临界值 8 ,当某一个桶中的链表节点数大于 8 则转为树
     */
    static final int TREEIFY_THRESHOLD = 8;
    /**
     * 需要重新转为链表的临界值 6 ,当某一个桶中的树节点数小于 6 则转为链表
     */
    static final int UNTREEIFY_THRESHOLD = 6;
    /**
     * 允许转为树的最小容量 64
     */
    static final int MIN_TREEIFY_CAPACITY = 64;
  1. 默认初始化容量:是在使用无初始化容量构造时,创建的初始数组容量大小,此种构造在新建时并不会创建数组,而是在进行首次存放元素时才会进行数组初始化
  2. 最大容量: 标准扩容(即常规的扩容方式,每次扩容是上一次容量的两倍)的最大容量,如果容量大于了这个值,则将容量扩容至 Integer.MAX_VALUE
  3. 默认加载因子: 在使用无加载因子构造时使用的默认的加载因子
  4. 树化临界值: 当某个桶中的链表节点数大于此值时,则转化为树
  5. 链表化临界值: 当某个桶中的链表节点数小于此值时,则转为链表
  6. 最小树化容量: 只有当当前散列表中的容量大于等的此值时,才允许将符合要求的链表转为树,否则就只进行扩容操作
2. 属性及描述:
// 表(节点数组)
    transient Node<K,V>[] table;
    // 节点集合
    transient Set<Map.Entry<K,V>> entrySet;
    // 大小:map中键值对的数量
    transient int size;
    // 结构上的修改次数 (添加或者删除, 查询或者修改值不会造成结构变化)
    transient int modCount;
    // 临界值
    int threshold;
    // 加载因子
    final float loadFactor;  
    // 键集合
   transient Set<K> keySet;
    // 值集合
   transient Collection<V> values;
  1. 表: table就是一个 Node<K,V> 数组,数组的长度就是散列表的容量,每一个数组元素就表示一个桶
  2. 节点集合: 存放所有节点的集合
  3. 大小: 当前散列表中目前元素个数
  4. 修改次数: 记录进行结构化修改的次数,用于判断同步,比较期望值和操作后的值是否一致,来判断是否同步
  5. 临界值: 用于判断是否需要扩容的临界值,当前值为当前容量乘以加载因子
  6. 加载因子: 用于计算散列表每次扩容的临界值
  7. 键集合和值集合:定义在 AbstractMap 中相关实现也是
3. 节点
  • 链节点

链表节点描述:用于存放每个键值对的键和值以及对应的哈希值和下一个节点

注意:
1.由下面的节点代码可以看出, JAVA中的散列表的元素为链表时是单向链表,因为只有指向下一个节点的next属性
2.节点的构造只有一个全参构造,所以在HashMap中才会出现next为null时仍要写的情况

static class Node<K,V> implements Map.Entry<K,V> {
	 // hash值
	 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; }
	 // 获取hash值
	 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;
	 }
 }
  • 树节点
    篇幅太长,移至文章结尾

树节点描述:树节点有两个结构:
一是双向链表,树节点的定义中既有指向上一节点的引用变量也有指向下一节点的引用变量(下一节点的变量定义是继承过来的);
二是树结构(红黑树),既有父级节点引用变量,也有左右子节点的引用变量,还有变量指明该节点是否是红节点.
树这一节点中有很多内容,本人就在此挖个坑,等本人把树吃透后来填

四. 一些重要的方法

1.hash
static final int hash(Object key) {
    int h;
    // 如果 h 小于2^(16-1)次幂,得到值仍为 h
    // 如果 h 大于2^16(16-1),得到的值为 h hash后的值,此值小于 2^16
    // 为什么时 2^16 ? 因为HashMap的容量是 int 类型,正数的最大值为 2^16 - 1
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

描述:
此方法是JAVA的HashMap中获取哈希值的方法,此处不纠结hash算法的值是怎样计算的,不同语言有不同的hash实现;
将此方法放在此处是想说明为什么HashMap中的key可以有null,因为key为null时,返回的hash值直接是 0 .

2.tableSizeFor
/**
* Returns a power of two size for the given target capacity.               为给定的容量返回一个2的整次幂大小
*/
// 结果是返回一个不小于给定值的最小2的整次幂数,用作表大小
static final int tableSizeFor(int cap) {
   int n = cap - 1;
   n |= n >>> 1;       // n = n | n >>> 1      从n的有效最高位(除了符号位以外的第一个 1 )开始的 2 位都为 1 (如果位数大于等于 2)
   n |= n >>> 2;       // n = n | n >>> 2      基于上一步,结果是从n的有效最高位(除了符号位以外的第一个 1 )开始的 4 位都为 1 (如果位数大于等于 4)
   n |= n >>> 4;       // n = n | n >>> 4      基于上一步,结果是从n的有效最高位(除了符号位以外的第一个 1 )开始的 8 位都为 1 (如果位数大于等于 8)
   n |= n >>> 8;       // n = n | n >>> 8      基于上一步,结果是从n的有效最高位(除了符号位以外的第一个 1 )开始的 16 位都为 1 (如果位数大于等于 16)
   n |= n >>> 16;      // n = n | n >>> 16     基于上一步,结果是从n的有效最高位(除了符号位以外的第一个 1 )开始的所有位都为 1
   // 以上算法会从 cap - 1 的有效最高位开始,后续位全部为 1
   // 如果小于0,就为1 ,否则如果大于等于最大容量,就为最大容量,否则就为不小于给定值的最小2的整次幂数
   return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}

描述:
上述方法中添加了注释, 对 n 的操作是无符号右移和按位或运算;
结果是返回了一个大于给定值同时又是 2 的整次幂的最小值

右移和或运算流程举例如下:

/*
一个 int 类型的值 n ,获取其二进制数,如:
n = 
0000 0000 0000 1010 0000 1100 0000 0000    (随便敲的,我也没计算是多少)
n >>> 1
0000 0000 0000 0101 0000 0110 0000 0000
n |= n >>> 1(按位或运算,有 1 则 1)
n = 
0000 0000 0000 1111 0000 1110 0000 0000
n >>> 2
0000 0000 0000 0011 1100 0011 1000 0000
n |= n >>> 2
n = 
0000 0000 0000 1111 1100 1111 1000 0000
n >>> 4
0000 0000 0000 0000 1111 1100 1111 1000
n |= n >>> 4
0000 0000 0000 1111 1111 1111 1111 1000
...
0000 0000 0000 1111 1111 1111 1111 1111
经过方法中描述的 5 次运算后,任何一个数都可以的到一个从最高有效位开始至结束全部为 1 的数
*/

注意:
1.是符合要求的任意一个数,哪怕 n 是 2 的整次幂(二进制数只有一个 1 )
2.由上述操作的到的数字加 1 之后,得到一个 2 的整次幂数, 这个数必然会大于给定的数,因为任意一个给定数,将其从最高有效位开始至结束位的所有位都置为 1 得到的数必然会大于等于该数,加 1 之后必然大于该数
3.为什么 n 要等于 给定值 cap 减 1 :影响该算法的结果的关键在于最高有效位位置:如果 cap 不是 2 的整次幂,则值是否减 1 是没有影响的;如果 cap 是 2 的整次幂,如果不减 1 ,最高有效位就是cap 的最高有效位,方法的返回值就是 cap 的两倍,如果减 1 ,最高有效位就是 cap 的最高有效位的下一位,方法的返回值就是 cap 值;

3.构造方法
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;
    // 不小于目标容量的最小 2 的整次幂
    this.threshold = tableSizeFor(initialCapacity);
}

public HashMap(int initialCapacity) {
   this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

public HashMap() {
    this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}

public HashMap(Map<? extends K, ? extends V> m) {
   this.loadFactor = DEFAULT_LOAD_FACTOR;
   putMapEntries(m, false);
}

描述:
1. 非集合构造方法中并没有创建散列表(节点数组)的操作,只是进行了加载因子和临界值的赋值;
2. 散列表的创建是在首次赋值时进行创建的

4.resize
/**
 * 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;
    // 旧容量大于 0 如果不是新new的哈希表的首次添加元素,则一定会执行此分支,
    // 结果是,每次扩容结果为之前容量的两倍或者是最大
    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
    }
    // 旧容量不大于 0 且旧临界值大于 0
    // TODO 什么情况下执行此分支?
    else if (oldThr > 0) 
    	// initial capacity was placed in threshold  初始化容量放置在临界值中
        // 新容量为旧的临界值
        newCap = oldThr;
    // 旧容量不大于 0 且旧临界值不大于 0 ,新new的哈希表首次添加元素是执行
    else {               // zero initial threshold signifies using defaults     从零开始初始化使用默认值
        newCap = DEFAULT_INITIAL_CAPACITY;
        newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
    }
    // 新临界值为 0 ,即旧容量不大于 0 且旧临界值大于 0 的情况
    // TODO 什么情况下会执行该分支
    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;
    // 扩容后重新计算元素位置,由于每次扩容的结果是原容量的两倍,所以结果就是原容量的二进制数左移一位
    // 计算元素在表中的位置时是用 e.hash & (table.length -1),获得一个小于表长度的数字作为元素在表中的数组下标
    // 如:0000 1011 & 0010 0000 - 1 = 0000 1011 & 0001 1111 = 0000 1011
    // 基于以上两条,计算元素在数组中的下标有没有发生变化关键是 e.hash 对应原容量的有效位的位置的值是否为 1 
    // 原因是计算时新容量比原容量多了一位计算位,产生异常就在该计算位的不同
    // 结果是要么不变,要么加上 oldCap
    // e.hash 对应原容量的有效位的位置为 0 --------> 结果不变
    // 如:  e.hash: 0000 1011
    //     oldCap: 0010 0000
    // 0000 1011 & 0010 0000 - 1 = 0000 1011 & 0001 1111 = 0000 1011
    // 0000 1011 & 0100 0000 - 1 = 0000 1011 & 0011 1111 = 0000 1011
    // e.hash 对应原容量的有效位的位置为 1 ---> 结果为原值加旧容量(即二进制数中多了旧容量有效位对应的 1 )
    // 如:  e.hash: 0010 1011
    //     oldCap: 0010 0000
    // 0010 1011 & 0010 0000 - 1 = 0010 1011 & 0001 1111 = 0000 1011
    // 0010 1011 & 0100 0000 - 1 = 0010 1011 & 0011 1111 = 0010 1011
    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)
                    // 重新hash,并将元素放到桶中
                    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;
                        // 由于容量值除了最高位为 1 以外,其他位全为 0 
                        // 所以,如果 & 运算结果位 0 ,那么 oldCap 的最高位对应的 e.hash 的该位为 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;
}

描述:
1.结果是返回了扩容后的新散列表
2.e.hash & (cap - 1) 这个运算: 前文中提及,每一个节点中都会保存该节点key对应的hash值, 使用容量减一(cap - 1)作为掩码,可以使任意的值计算得到一个小于 cap 的值,这个值在 0 到 (cap - 1)之间,也刚好契合数组下标
3.原因: cap 是一个 2 的整次幂数, 减一之后得到的数 n 是最高有效位之前全为 0 ,从最高有效位开始全为 1 ,进行 & 运算(有 0 则 0)后得到的结果 m ,最高有效位之前全部为 0 ,所以 m 不可能大于 n,必然小于 n + 1
4.为什么建议在大致知道要添加到散列表中数量时,传入容量值: resize过程中会对散列表中的元素重新哈希寻找位置,不断的resize很耗费性能,使用容量构造可以减少或者避免重新哈希

5.putVal
/**
 * 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) {
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    // 如果没有表,初始化容量(默认值)
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
    // 节点对应数组下标位置元素为 null ,即不存在该元素
    if ((p = tab[i = (n - 1) & hash]) == null)
        // 新建一个节点
        tab[i] = newNode(hash, key, value, null);
    else {
        // 存放 key 相同的旧节点,不为 null 表示存在旧节点,为 null 表示不存在
        Node<K,V> e; K k;
        // 如果hash值相同并且key也相同
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            // 将该节点赋给 e
            e = p;
        else if (p instanceof TreeNode)
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        // 不相同,遍历链表
        else {
            for (int binCount = 0; ; ++binCount) {
                // 如果链表中某一节点的 next 为 null 不存在值为该 key 的节点,就新建一个节点,跳出循环
                if ((e = p.next) == null) {
                    // 新建一个节点
                    p.next = newNode(hash, key, value, null);
                    // 如果达到了树化临界值,就进行树化
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        treeifyBin(tab, hash);
                    break;
                }
                // 如果节点的hash值相同并且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;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    // 如果是新添加节点,则修改次数和大小自增,如果大小大于临界值,就重新计算容量
    ++modCount;
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}

描述:
1. 添加元素的主要方法,会先判断是否已经有了散列表,如果没有会先创建散列表;
2. 如果目标key已经存在相应的节点,就将原值替换并返回

6.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) {
        // 如果还没有table
        if (table == null) { // pre-size
            // 大小除以加载因子加 1 ,加 1 是为了消除小数的影响
            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);
        }
    }
}

描述: 是添加节点的主要方法,主要用于集合构造和putAll,clone方法中也用到了

7.removeNode
/**
 * Implements Map.remove and related methods.
 *
 * @param hash hash for key
 * @param key the key
 * @param value the value to match if matchValue, else ignored
 * @param matchValue if true only remove if value is equal
 * @param movable if false do not move other nodes while removing
 * @return the node, or null if none
 */
final Node<K,V> removeNode(int hash, Object key, Object value,
                           boolean matchValue, boolean movable) {
    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<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);
            }
        }
        if (node != null && (!matchValue || (v = node.value) == value ||
                             (value != null && value.equals(v)))) {
            if (node instanceof TreeNode)
                ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
            else if (node == p)
                tab[index] = node.next;
            else
                p.next = node.next;
            // 修改次数自增,大小自减
            ++modCount;
            --size;
            afterNodeRemoval(node);
            return node;
        }
    }
    return null;
}

描述:移除一个节点,先找桶判断有没有节点,节点数量是否大于 1 ,返回删除的节点

8.getNode
/**
 * 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;
    // 数组存在并且 key 对应的桶位置不为 null
    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;
}

描述:查找节点,返回定位节点

9.treeifyBin
/**
 * Replaces all linked nodes in bin at index for given hash unless
 * table is too small, in which case resizes instead.
 */
final void treeifyBin(Node<K,V>[] tab, int hash) {
    int n, index; Node<K,V> e;
    // 未达到最小树化容量(64)就只进行扩容
    if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
        resize();
    // 表中在该桶中有节点(不判断数量,默认该桶中的节点数大于等于8)
    else if ((e = tab[index = (n - 1) & hash]) != null) {
        // 头和尾
        TreeNode<K,V> hd = null, tl = null;
        // 遍历链表,结果是的到一个双向链表
        do {
            TreeNode<K,V> p = replacementTreeNode(e, null);
            // 赋值头节点
            if (tl == null)
                hd = p;
            else {
                // 新节点的前一个节点是尾节点
                p.prev = tl;
                // 尾节点的下一个节点是新节点
                tl.next = p;
            }
            // 每次都将尾节点更新(尾指针后移)
            tl = p;
            // 指针后移
        } while ((e = e.next) != null);
        // 树化
        if ((tab[index] = hd) != null)
            hd.treeify(tab);
    }
}

描述:将桶进行树化的方法,从中可以找到判断当前散列表容量是否大于最小树化容量,如果小于就只进行扩容

五.常用方法

1.put
public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}
2.putAll
public void putAll(Map<? extends K, ? extends V> m) {
    putMapEntries(m, true);
}

上面两个方法都是存放元素,直接调用存放元素值或者节点的方法

3.get
public V get(Object key) {
    Node<K,V> e;
    return (e = getNode(hash(key), key)) == null ? null : e.value;
}
4.containsKey
public boolean containsKey(Object key) {
    return getNode(hash(key), key) != null;
}
5.replace
public V replace(K key, V value) {
    Node<K,V> e;
    if ((e = getNode(hash(key), key)) != null) {
        V oldValue = e.value;
        e.value = value;
        afterNodeAccess(e);
        return oldValue;
    }
    return null;
}

上面三个方法是直接调用查找节点的方法,然后进行后续操作

6.remove
public boolean remove(Object key, Object value) {
    return removeNode(hash(key), key, value, true, true) != null;
}

移除方法是直接调用移除节点的方法

7.containsValue
public boolean containsValue(Object value) {
    Node<K,V>[] tab; V v;
    if ((tab = table) != null && size > 0) {
        for (int i = 0; i < tab.length; ++i) {
            for (Node<K,V> e = tab[i]; e != null; e = e.next) {
                if ((v = e.value) == value ||
                    (value != null && value.equals(v)))
                    return true;
            }
        }
    }
    return false;
}
8.clear
public void clear() {
    Node<K,V>[] tab;
    // 修改次数自增
    modCount++;
    if ((tab = table) != null && size > 0) {
        // 遍历清空表
        size = 0;
        for (int i = 0; i < tab.length; ++i)
            tab[i] = null;
    }
}
9.forEach
public void forEach(BiConsumer<? super K, ? super V> action) {
    Node<K,V>[] tab;
    if (action == null)
        throw new NullPointerException();
    if (size > 0 && (tab = table) != null) {
        int mc = modCount;
        for (int i = 0; i < tab.length; ++i) {
            for (Node<K,V> e = tab[i]; e != null; e = e.next)
                action.accept(e.key, e.value);
        }
        if (modCount != mc)
            throw new ConcurrentModificationException();
    }
}

上面三个方法是直接遍历整个集合,注意与containsKey的实现区别,key可以通过哈希值直接获取

10.keySet
public Set<K> keySet() {
    Set<K> ks = keySet;
    if (ks == null) {
        ks = new KeySet();
        keySet = ks;
    }
    return ks;
}
11.values
public Collection<V> values() {
    Collection<V> vs = values;
    if (vs == null) {
        vs = new Values();
        values = vs;
    }
    return vs;
}
12.entrySet
public Set<Map.Entry<K,V>> entrySet() {
    Set<Map.Entry<K,V>> es;
    return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
}
13.isEmpty
public boolean isEmpty() {
    return size == 0;
}
14.size
public boolean isEmpty() {
    return size == 0;
}

以上五个方法是直接对散列表属性进行操作

树节点代码:

static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
       TreeNode<K,V> parent;  // red-black tree links
       TreeNode<K,V> left;
       TreeNode<K,V> right;
       TreeNode<K,V> prev;    // needed to unlink next upon deletion
       boolean red;
       TreeNode(int hash, K key, V val, Node<K,V> next) {
           super(hash, key, val, next);
       }

       /**
        * Returns root of tree containing this node.
        */
       final TreeNode<K,V> root() {
           for (TreeNode<K,V> r = this, p;;) {
               if ((p = r.parent) == null)
                   return r;
               r = p;
           }
       }

       /**
        * Ensures that the given root is the first node of its bin.
        */
       static <K,V> void moveRootToFront(Node<K,V>[] tab, TreeNode<K,V> root) {
           int n;
           if (root != null && tab != null && (n = tab.length) > 0) {
               int index = (n - 1) & root.hash;
               TreeNode<K,V> first = (TreeNode<K,V>)tab[index];
               if (root != first) {
                   Node<K,V> rn;
                   tab[index] = root;
                   TreeNode<K,V> rp = root.prev;
                   if ((rn = root.next) != null)
                       ((TreeNode<K,V>)rn).prev = rp;
                   if (rp != null)
                       rp.next = rn;
                   if (first != null)
                       first.prev = root;
                   root.next = first;
                   root.prev = null;
               }
               assert checkInvariants(root);
           }
       }

       /**
        * Finds the node starting at root p with the given hash and key.
        * The kc argument caches comparableClassFor(key) upon first use
        * comparing keys.
        */
       final TreeNode<K,V> find(int h, Object k, Class<?> kc) {
           TreeNode<K,V> p = this;
           do {
               int ph, dir; K pk;
               TreeNode<K,V> pl = p.left, pr = p.right, q;
               if ((ph = p.hash) > h)
                   p = pl;
               else if (ph < h)
                   p = pr;
               else if ((pk = p.key) == k || (k != null && k.equals(pk)))
                   return p;
               else if (pl == null)
                   p = pr;
               else if (pr == null)
                   p = pl;
               else if ((kc != null ||
                         (kc = comparableClassFor(k)) != null) &&
                        (dir = compareComparables(kc, k, pk)) != 0)
                   p = (dir < 0) ? pl : pr;
               else if ((q = pr.find(h, k, kc)) != null)
                   return q;
               else
                   p = pl;
           } while (p != null);
           return null;
       }

       /**
        * Calls find for root node.
        */
       final TreeNode<K,V> getTreeNode(int h, Object k) {
           return ((parent != null) ? root() : this).find(h, k, null);
       }

       /**
        * Tie-breaking utility for ordering insertions when equal
        * hashCodes and non-comparable. We don't require a total
        * order, just a consistent insertion rule to maintain
        * equivalence across rebalancings. Tie-breaking further than
        * necessary simplifies testing a bit.
        */
       static int tieBreakOrder(Object a, Object b) {
           int d;
           if (a == null || b == null ||
               (d = a.getClass().getName().
                compareTo(b.getClass().getName())) == 0)
               d = (System.identityHashCode(a) <= System.identityHashCode(b) ?
                    -1 : 1);
           return d;
       }

       /**
        * Forms tree of the nodes linked from this node.
        */
       // 树化
       final void treeify(Node<K,V>[] tab) {
           TreeNode<K,V> root = null;
           // 遍历双向链表
           for (TreeNode<K,V> x = this, next; x != null; x = next) {
               next = (TreeNode<K,V>)x.next;
               x.left = x.right = null;
               // 首次赋值根节点
               if (root == null) {
                   x.parent = null;
                   x.red = false;
                   root = x;
               }
               else {
                   // 当前节点key
                   K k = x.key;
                   // 当前节点hash
                   int h = x.hash;
                   Class<?> kc = null;
                   for (TreeNode<K,V> p = root;;) {
                       int dir, ph;
                       K pk = p.key;
                       // 当前节点hash小,左节点
                       if ((ph = p.hash) > h)
                           dir = -1;
                       // 当前节点hash大,右节点
                       else if (ph < h)
                           dir = 1;
                       else if ((kc == null &&
                                 (kc = comparableClassFor(k)) == null) ||
                                (dir = compareComparables(kc, k, pk)) == 0)
                           dir = tieBreakOrder(k, pk);
                       // 定义当前节点的父节点
                       TreeNode<K,V> xp = p;
                       if ((p = (dir <= 0) ? p.left : p.right) == null) {
                           x.parent = xp;
                           if (dir <= 0)
                               xp.left = x;
                           else
                               xp.right = x;
                           root = balanceInsertion(root, x);
                           break;
                       }
                   }
               }
           }
           moveRootToFront(tab, root);
       }

       /**
        * Returns a list of non-TreeNodes replacing those linked from
        * this node.
        */
       final Node<K,V> untreeify(HashMap<K,V> map) {
           Node<K,V> hd = null, tl = null;
           for (Node<K,V> q = this; q != null; q = q.next) {
               Node<K,V> p = map.replacementNode(q, null);
               if (tl == null)
                   hd = p;
               else
                   tl.next = p;
               tl = p;
           }
           return hd;
       }

       /**
        * Tree version of putVal.
        */
       final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
                                      int h, K k, V v) {
           Class<?> kc = null;
           boolean searched = false;
           TreeNode<K,V> root = (parent != null) ? root() : this;
           for (TreeNode<K,V> p = root;;) {
               int dir, ph; K pk;
               if ((ph = p.hash) > h)
                   dir = -1;
               else if (ph < h)
                   dir = 1;
               else if ((pk = p.key) == k || (k != null && k.equals(pk)))
                   return p;
               else if ((kc == null &&
                         (kc = comparableClassFor(k)) == null) ||
                        (dir = compareComparables(kc, k, pk)) == 0) {
                   if (!searched) {
                       TreeNode<K,V> q, ch;
                       searched = true;
                       if (((ch = p.left) != null &&
                            (q = ch.find(h, k, kc)) != null) ||
                           ((ch = p.right) != null &&
                            (q = ch.find(h, k, kc)) != null))
                           return q;
                   }
                   dir = tieBreakOrder(k, pk);
               }

               TreeNode<K,V> xp = p;
               if ((p = (dir <= 0) ? p.left : p.right) == null) {
                   Node<K,V> xpn = xp.next;
                   TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn);
                   if (dir <= 0)
                       xp.left = x;
                   else
                       xp.right = x;
                   xp.next = x;
                   x.parent = x.prev = xp;
                   if (xpn != null)
                       ((TreeNode<K,V>)xpn).prev = x;
                   moveRootToFront(tab, balanceInsertion(root, x));
                   return null;
               }
           }
       }

       /**
        * Removes the given node, that must be present before this call.
        * This is messier than typical red-black deletion code because we
        * cannot swap the contents of an interior node with a leaf
        * successor that is pinned by "next" pointers that are accessible
        * independently during traversal. So instead we swap the tree
        * linkages. If the current tree appears to have too few nodes,
        * the bin is converted back to a plain bin. (The test triggers
        * somewhere between 2 and 6 nodes, depending on tree structure).
        */
       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;
           TreeNode<K,V> first = (TreeNode<K,V>)tab[index], root = first, rl;
           TreeNode<K,V> succ = (TreeNode<K,V>)next, pred = prev;
           if (pred == null)
               tab[index] = first = succ;
           else
               pred.next = succ;
           if (succ != null)
               succ.prev = pred;
           if (first == null)
               return;
           if (root.parent != null)
               root = root.root();
           if (root == null
               || (movable
                   && (root.right == null
                       || (rl = root.left) == null
                       || rl.left == null))) {
               tab[index] = first.untreeify(map);  // too small
               return;
           }
           TreeNode<K,V> p = this, pl = left, pr = right, replacement;
           if (pl != null && pr != null) {
               TreeNode<K,V> s = pr, sl;
               while ((sl = s.left) != null) // find successor
                   s = sl;
               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;
               if (s == pr) { // p was s's direct parent
                   p.parent = s;
                   s.right = p;
               }
               else {
                   TreeNode<K,V> sp = s.parent;
                   if ((p.parent = sp) != null) {
                       if (s == sp.left)
                           sp.left = p;
                       else
                           sp.right = p;
                   }
                   if ((s.right = pr) != null)
                       pr.parent = s;
               }
               p.left = null;
               if ((p.right = sr) != null)
                   sr.parent = p;
               if ((s.left = pl) != null)
                   pl.parent = s;
               if ((s.parent = pp) == null)
                   root = s;
               else if (p == pp.left)
                   pp.left = s;
               else
                   pp.right = s;
               if (sr != null)
                   replacement = sr;
               else
                   replacement = p;
           }
           else if (pl != null)
               replacement = pl;
           else if (pr != null)
               replacement = pr;
           else
               replacement = p;
           if (replacement != p) {
               TreeNode<K,V> pp = replacement.parent = p.parent;
               if (pp == null)
                   root = replacement;
               else if (p == pp.left)
                   pp.left = replacement;
               else
                   pp.right = replacement;
               p.left = p.right = p.parent = null;
           }

           TreeNode<K,V> r = p.red ? root : balanceDeletion(root, replacement);

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

       /**
        * Splits nodes in a tree bin into lower and upper tree bins,
        * or untreeifies if now too small. Called only from resize;
        * see above discussion about split bits and indices.
        *
        * @param map the map
        * @param tab the table for recording bin heads
        * @param index the index of the table being split
        * @param bit the bit of hash to split on
        */
       final void split(HashMap<K,V> map, Node<K,V>[] tab, int index, int bit) {
           TreeNode<K,V> b = this;
           // Relink into lo and hi lists, preserving order
           TreeNode<K,V> loHead = null, loTail = null;
           TreeNode<K,V> hiHead = null, hiTail = null;
           int lc = 0, hc = 0;
           for (TreeNode<K,V> e = b, next; e != null; e = next) {
               next = (TreeNode<K,V>)e.next;
               e.next = null;
               if ((e.hash & bit) == 0) {
                   if ((e.prev = loTail) == null)
                       loHead = e;
                   else
                       loTail.next = e;
                   loTail = e;
                   ++lc;
               }
               else {
                   if ((e.prev = hiTail) == null)
                       hiHead = e;
                   else
                       hiTail.next = e;
                   hiTail = e;
                   ++hc;
               }
           }

           if (loHead != null) {
               if (lc <= UNTREEIFY_THRESHOLD)
                   tab[index] = loHead.untreeify(map);
               else {
                   tab[index] = loHead;
                   if (hiHead != null) // (else is already treeified)
                       loHead.treeify(tab);
               }
           }
           if (hiHead != null) {
               if (hc <= UNTREEIFY_THRESHOLD)
                   tab[index + bit] = hiHead.untreeify(map);
               else {
                   tab[index + bit] = hiHead;
                   if (loHead != null)
                       hiHead.treeify(tab);
               }
           }
       }

       /* ------------------------------------------------------------ */
       // Red-black tree methods, all adapted from CLR

       static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
                                             TreeNode<K,V> p) {
           TreeNode<K,V> r, pp, rl;
           if (p != null && (r = p.right) != null) {
               if ((rl = p.right = r.left) != null)
                   rl.parent = p;
               if ((pp = r.parent = p.parent) == null)
                   (root = r).red = false;
               else if (pp.left == p)
                   pp.left = r;
               else
                   pp.right = r;
               r.left = p;
               p.parent = r;
           }
           return root;
       }

       static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
                                              TreeNode<K,V> p) {
           TreeNode<K,V> l, pp, lr;
           if (p != null && (l = p.left) != null) {
               if ((lr = p.left = l.right) != null)
                   lr.parent = p;
               if ((pp = l.parent = p.parent) == null)
                   (root = l).red = false;
               else if (pp.right == p)
                   pp.right = l;
               else
                   pp.left = l;
               l.right = p;
               p.parent = l;
           }
           return root;
       }

       static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
                                                   TreeNode<K,V> x) {
           x.red = true;
           for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
               if ((xp = x.parent) == null) {
                   x.red = false;
                   return x;
               }
               else if (!xp.red || (xpp = xp.parent) == null)
                   return root;
               if (xp == (xppl = xpp.left)) {
                   if ((xppr = xpp.right) != null && xppr.red) {
                       xppr.red = false;
                       xp.red = false;
                       xpp.red = true;
                       x = xpp;
                   }
                   else {
                       if (x == xp.right) {
                           root = rotateLeft(root, x = xp);
                           xpp = (xp = x.parent) == null ? null : xp.parent;
                       }
                       if (xp != null) {
                           xp.red = false;
                           if (xpp != null) {
                               xpp.red = true;
                               root = rotateRight(root, xpp);
                           }
                       }
                   }
               }
               else {
                   if (xppl != null && xppl.red) {
                       xppl.red = false;
                       xp.red = false;
                       xpp.red = true;
                       x = xpp;
                   }
                   else {
                       if (x == xp.left) {
                           root = rotateRight(root, x = xp);
                           xpp = (xp = x.parent) == null ? null : xp.parent;
                       }
                       if (xp != null) {
                           xp.red = false;
                           if (xpp != null) {
                               xpp.red = true;
                               root = rotateLeft(root, xpp);
                           }
                       }
                   }
               }
           }
       }

       static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
                                                  TreeNode<K,V> x) {
           for (TreeNode<K,V> xp, xpl, xpr;;) {
               if (x == null || x == root)
                   return root;
               else if ((xp = x.parent) == null) {
                   x.red = false;
                   return x;
               }
               else if (x.red) {
                   x.red = false;
                   return root;
               }
               else if ((xpl = xp.left) == x) {
                   if ((xpr = xp.right) != null && xpr.red) {
                       xpr.red = false;
                       xp.red = true;
                       root = rotateLeft(root, xp);
                       xpr = (xp = x.parent) == null ? null : xp.right;
                   }
                   if (xpr == null)
                       x = xp;
                   else {
                       TreeNode<K,V> sl = xpr.left, sr = xpr.right;
                       if ((sr == null || !sr.red) &&
                           (sl == null || !sl.red)) {
                           xpr.red = true;
                           x = xp;
                       }
                       else {
                           if (sr == null || !sr.red) {
                               if (sl != null)
                                   sl.red = false;
                               xpr.red = true;
                               root = rotateRight(root, xpr);
                               xpr = (xp = x.parent) == null ?
                                   null : xp.right;
                           }
                           if (xpr != null) {
                               xpr.red = (xp == null) ? false : xp.red;
                               if ((sr = xpr.right) != null)
                                   sr.red = false;
                           }
                           if (xp != null) {
                               xp.red = false;
                               root = rotateLeft(root, xp);
                           }
                           x = root;
                       }
                   }
               }
               else { // symmetric
                   if (xpl != null && xpl.red) {
                       xpl.red = false;
                       xp.red = true;
                       root = rotateRight(root, xp);
                       xpl = (xp = x.parent) == null ? null : xp.left;
                   }
                   if (xpl == null)
                       x = xp;
                   else {
                       TreeNode<K,V> sl = xpl.left, sr = xpl.right;
                       if ((sl == null || !sl.red) &&
                           (sr == null || !sr.red)) {
                           xpl.red = true;
                           x = xp;
                       }
                       else {
                           if (sl == null || !sl.red) {
                               if (sr != null)
                                   sr.red = false;
                               xpl.red = true;
                               root = rotateLeft(root, xpl);
                               xpl = (xp = x.parent) == null ?
                                   null : xp.left;
                           }
                           if (xpl != null) {
                               xpl.red = (xp == null) ? false : xp.red;
                               if ((sl = xpl.left) != null)
                                   sl.red = false;
                           }
                           if (xp != null) {
                               xp.red = false;
                               root = rotateRight(root, xp);
                           }
                           x = root;
                       }
                   }
               }
           }
       }

       /**
        * Recursive invariant check
        */
       static <K,V> boolean checkInvariants(TreeNode<K,V> t) {
           TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
               tb = t.prev, tn = (TreeNode<K,V>)t.next;
           if (tb != null && tb.next != t)
               return false;
           if (tn != null && tn.prev != t)
               return false;
           if (tp != null && t != tp.left && t != tp.right)
               return false;
           if (tl != null && (tl.parent != t || tl.hash > t.hash))
               return false;
           if (tr != null && (tr.parent != t || tr.hash < t.hash))
               return false;
           if (t.red && tl != null && tl.red && tr != null && tr.red)
               return false;
           if (tl != null && !checkInvariants(tl))
               return false;
           if (tr != null && !checkInvariants(tr))
               return false;
           return true;
       }
   }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值