八股文:集合知识图谱——HashMap篇

Collections
其中黑方块表示接口,深灰方块表示抽象类,浅灰方块表示具体类
粗线表示继承,细线表示实现接口

一、HashMap原码剖析

文中没有把所有语句都放上来,只放有必要知道和解读的
其实很多疑惑的点在原码中都能看出解答,如:key和value能否为null,如果key为null,放在哪?为什么HashMap的长度是2的幂次方?HashMap为什么不是线程安全的? 等等

1、类变量

/**
 * The default initial capacity - MUST be a power of two.
 */
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;

若不规定HashMap的大小,则初始化时会以16的size进行初始化

/**
 * The maximum capacity.
 */
static final int MAXIMUM_CAPACITY = 1 << 30;

HashMap的最大容量为2的30次方

/**
 * The load factor used when none specified in constructor.
 */
static final float DEFAULT_LOAD_FACTOR = 0.75f;

填充因子:当map中node数量达到当前容量的0.75倍时,进行扩容

/**
 * The bin count threshold for using a tree rather than list for a bin.
 */
static final int TREEIFY_THRESHOLD = 8;
/**
 * The bin count threshold for untreeifying a (split) bin during a resize operation.
 */
static final int UNTREEIFY_THRESHOLD = 6;

树化阈值:(下面会提到,应先达到树化容量后)当一个桶(即数组中的一个位置)内的node数量达到8时,链表转化为红黑树
链化阈值:当红黑树的node数量为6时,红黑树退化为链表

/**
 * The smallest table capacity for which bins may be treeified.
 * (Otherwise the table is resized if too many nodes in a bin.)
 */
static final int MIN_TREEIFY_CAPACITY = 64;

树化容量:当map的容量达到64之后才会树化,否则即使达到了树化阈值也只会扩容

/**
 * The load factor for the hash table.
 */
final float loadFactor;

/**
 * The next size value at which to resize (capacity * load factor).
 */
int threshold;

HashMap初始化时时可以自定义装载因子的,若不自定义便取DEFAULT_LOAD_FACTOR = 0.75f
threshold便是由当前数组长度 * 装载因子,也就是触发扩容的装载量

/**
 * This field is used to make iterators on Collection-views of
 * the HashMap fail-fast.  (See ConcurrentModificationException).
 */
transient int modCount;

modCount:记录map被修改的次数,每修改一次便自增

fail-fast机制:快速失败。在利用Iterator对HashMap迭代的过程中,迭代器初始化时会记录当前的modCount,在迭代过程中,每一次的next()方法都会判断所记录的modCount和当前map的modCount是否相同。也就是说在对map进行迭代时倘若发生了修改就会触发机制抛出异常。

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

在HashMap的构造函数中,table是没有被初始化的,也是允许长度为0的,于是可以看到在get()put()中,都会先判断table是否是null或长度是否为0的情况,为什么不实现初始化呢?
因为map可以手动输入大小,但倘若长时间内没有放入元素会浪费空间,尤其是当输入的长度比较大的时候

static class Node<K,V> implements Map.Entry<K,V> {
    final int hash;
    final K key;
    V value;
    Node<K,V> next;
    ...
}

关于泛型便不在这里展开讲了

2、类方法

public HashMap(int initialCapacity, float loadFactor) {
	... // 省略了部分代码
	this.loadFactor = loadFactor;
	this.threshold = tableSizeFor(initialCapacity);
}
/**
 * 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;
}

HashMap初始化时可以自定义长度,但其实是寻找第一个 >= cap而2的幂次数,如15转化为1616转化为1617转化为32

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

可以看出,HashMap是允许key为null的,当为null时,hash值为0,也就是说,key为null的结点会被放在第1个桶内,也即0号桶
此函数相当于二次hash,希望通过二次散列让hashCode的高16位和低16位异或使得散列更均匀

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

public boolean containsKey(Object key) {
    return getNode(hash(key), key) != null;
}

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 && // 1,解析在下方
        (first = tab[(n - 1) & hash]) != null) { // 2,解析在下方
        // 获取到的first为桶中的第一个元素,也即链表头
        if (first.hash == hash && // always check first node
            ((k = first.key) == key || (key != null && key.equals(k)))) // match
            return first;
        if ((e = first.next) != null) {
        	// 倘若当前桶内已经树化,则调用树中的寻找方法 
            if (first instanceof TreeNode)
                return ((TreeNode<K,V>)first).getTreeNode(hash, key);
            do { // 否则还是链式,则直接用while寻找
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    return e;
            } while ((e = e.next) != null);
        }
    }
    return null;
}

1)前面提到table可能未初始化或长度为0,所以先进行判断
2)(n - 1) & hash表示hash与长度取模,倘若map的长度是2的幂次,可以通过位运算来代替取模运算,这也是为什么HashMap长度是2的幂次的原因——位运算的速度比取模更快

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)
        n = (tab = resize()).length; // resize()用于扩容或初始化
    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) { // 1,解析在下方
                    p.next = newNode(hash, key, value, null);
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                    	// 此方法内部会先对map长度进行判断是否达到树化长度
                        treeifyBin(tab, hash); 
                    break;
                }
                // 在链表中寻找的过程中发现key已经出现过,则break
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    break;
                p = e;
            }
        }
        // 若key出现过则替换并返回就value
        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); // 面向LinkedHashMap提供的方法,可忽略
    return null;
}

1)找到尾部进行插入,这也是Java8对比于Java7更新的一点,防止形成循环链表。Java7中采用的是头插法,在并发的场景下,若map在进行扩容则容易生成环形链表。具体内容可以自行探索:Java HashMap的死循环

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
            threshold = Integer.MAX_VALUE;
            return oldTab;
        }
        // 可以看到,数组长度增大一倍,装载量threshold也增大一倍,填充因子保持不变
        else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && 
                oldCap >= DEFAULT_INITIAL_CAPACITY)
            newThr = oldThr << 1; // double threshold
    }
    // 若table没有被初始化,且照构造时输入了相关参数,则按计算得到的cap进行初始化
    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;
    // 1,解析在下方
    if (oldTab != null) {
        for (int j = 0; j < oldCap; ++j) {
            Node<K,V> e;
            if ((e = oldTab[j]) != null) {
            	// 拿到链表头,旧数组置空(虽然我也不知道为什么要null,可能为了更好的GC
                oldTab[j] = null; 
                if (e.next == null) // 如果链只有一个结点,相当于直接给newTable插入一个结点
                    newTab[e.hash & (newCap - 1)] = e;
                else if (e instanceof TreeNode) // 如果是树结点,直接调用树结点的相关方法
                    ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                else { // preserve order
                	// 否则会根据一定的条件将当前的链散列成两条链low和high
                    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) { // 依据此条件划分low和high
                            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;
                        // low放回与oldTable同下标的位置
                        newTab[j] = loHead; 
                    }
                    if (hiTail != null) {
                        hiTail.next = null;
                        // high放回与oldTable同下标 + oldCap的位置
                        newTab[j + oldCap] = hiHead; 
                    }
                }
            }
        }
    }
    return newTab;
}

1)Java8中结点的散列比Java7中更加快捷且简单,具体更新了哪些不同可以自行翻Java7原码

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

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 { // while循环找结点
                    if (e.hash == hash &&
                        ((k = e.key) == key ||
                         (key != null && key.equals(k)))) {
                        node = e;
                        break;
                    }
                    p = e; // p总是是e的父结点
                } while ((e = e.next) != null);
            }
        }
        // 如果node存在,则移除,否则返回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,p总是是e的父结点
                p.next = node.next;
            ++modCount;
            --size;
            afterNodeRemoval(node);
            return node;
        }
    }
    return null;
}

到此HashMap原码算是分析完毕了,还剩下的是红黑树的添加,删除,树化等相关方法,可以自行了解红黑树,或是自己写一棵红黑树出来便什么都懂了

二、HashMap的横向比较

1、HashMap、HashSet、TreeMap与HashTable

1)HashMap与HashSet

如果翻过HashSet原码就会知道,HashSet底层就是HashMap

private transient HashMap<E,Object> map;

// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();

public HashSet() {
    map = new HashMap<>();
}

public boolean add(E e) {
    return map.put(e, PRESENT)==null;
}

HashSet的几乎所有方法都是用HashMap来完成的

2)HashMap与TreeMap

1、TreeMap比HashMap多实现了SortedMap的接口,也就是多了排序功能
2、TreeMap的底层是红黑树实现的
翻看TreeMap原码,TreeMap的结点定义如下

static final class Entry<K,V> implements Map.Entry<K,V> {
    K key;
    V value;
    Entry<K,V> left;
    Entry<K,V> right;
    Entry<K,V> parent;
    boolean color = BLACK;
}

3)HashMap与HashTable

Ⅰ、HashMap线程不安全,HashTable线程安全
HashTable使用了全局的synchronized关键字,也就是最多只有一个线程能修改HashTable,效率很低
Ⅱ、HashMap默认初始值为16且长度一定为2的幂次,扩容为2倍扩容;HashTable为11,扩容为2n + 1
Ⅲ、Java8中HashMap引入树化,HashTable只有链表
Ⅳ、HashMap支持key和value为null,HashTable不支持

2、HashMap与ConcurrentHashMap

1)Java7中HashMap和ConcurrentHashMap都是数组+链表
Java8中HashMap和ConcurrentHashMap都是数组+链表/红黑树
换句话说,ConcurrentHashMap就是用来解决HashMap的并发问题的
2)HashMap线程不安全,ConcurrentHashMap线程安全
Java7中,ConcurrentHashMap采用分段锁(Segment)来保证线程安全,相当于把数组分段,每一段都有自己的锁,这样相比于HashTable,ConcurrentHashMap允许多个线程进行修改不同的分段,但同一分段内仍只允许一个线程修改
Java8中,ConcurrentHashMap抛弃了分段锁,采用CASsynchronized来保证线程安全
CAS是一种自旋机制,ConcurrentHashMap大量采用了这种机制来减少synchronized的使用,但仍需要用到锁,如扩容的时候要锁定链表头
推荐翻阅ConcurrentHashMap的源码来分析

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值