HashMap1.8 的源码解析

结构

HashMap的结构为数组+链表+红黑树。

//对象数组
transient Node<K,V>[] table; 
// 链表节点
static class Node<K,V> implements Map.Entry<K,V> {
        final int hash; //哈希值
        final K key; //建
        V value; //值
        Node<K,V> next;  //下一个节点
}
//红黑树节点
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;
}

在这里插入图片描述

HashMap使用“拉链法”解决了哈希冲突。

主要属性

static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // 默认初始容量为16
static final int MAXIMUM_CAPACITY = 1 << 30; //最大容量
static final float DEFAULT_LOAD_FACTOR = 0.75f; // 负载因子,默认为0.75
static final int TREEIFY_THRESHOLD = 8; //树化阈值,大于这个阈值,会将链表转化为红黑树,默认是8

关于负载因子,doc 的解释为:

默认负载因子为0.75的时候在时间和空间成本上提供了很好的折衷。太高了可以减少空间开销,但是会增加查找复杂度。我们设置负载因子尽量减少rehash的操作,但是查找元素的也要有性能保证。

HashMap (Java Platform SE 8 )

主要方法

HashMap主要的三个方法为:put()、get()、resize()。

put方法

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

//主要逻辑在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;
	//如果数组为空,则先进行扩容
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
	// i = (n - 1) & hash计算元素的下标,如果所在的桶为空,则新建一个节点
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null); 
    else {
        Node<K,V> e; K k;
		//如果元素的key与桶的key一样,则直接覆盖
        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);
					//如果链表长度大于8,则进行树化。
					//因为binCount是从0开始计算的,到满足下面条件时binCount为7,
					//再加上上面新的节点,所以此时链表有9个节点,所以链表长度大于8才会进行树化。
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        treeifyBin(tab, hash);
                    break;
                }
				// 如果存在相同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;
}

元素位置是通过 i = (n - 1) & hash来计算的, n为数组的长度, hash是通过 hash(key) 方法产生的。

hash(key)方法通过将 key 的 hashcode 与该 hashcode 的高 16 位按位异或,获得新的 hash。使用这种方法产生 hash 是为了充分利用 hashcode,减少冲突的发生。因为数组长度为 2^n,直接使用 hashcode % n 计算元素位置会导致只是利用到 hashcode 的低 n 位,而 hashcode 有 32 位,这样容易发生碰撞。

同时 hash(key)方法同时表明了,如果存在 key 为 null,则会放在下标为 0 的桶上。

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

当 n 位 2^n 时, hash % n = hash & (n -1),而且位运算的效率要比求余运算要快。

该方法主要做了:

  1. 判断数组是否为空,为空则进行扩容。
  2. 元素位置在数组中是否为空,为空则直接插进去。
    1. 不为空的话,说明已经存在值。判断该值的 key 与要插入的 key 是否相等,相等则覆盖值。
    2. 不相等的话,判断是否为红黑树,是的话,插入红黑树中。
    3. 不是红黑树的话,遍历链表,如果已经存在 key,则覆盖。否则,在链尾插入值。如果链表长度超过 8 ,则将链表转化为红黑树。
  3. 如果扩容后容量超过阈值 threshold,则进行扩容。

resize()方法

该方法用于扩容。

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"})
	// 新数组
    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;
						//如果新增bit位为0,则说明该节点在原位置,则将它挂到原位置的链表
                        if ((e.hash & oldCap) == 0) {
                            if (loTail == null)
                                loHead = e;
                            else
                                loTail.next = e;
                            loTail = e;
                        }
						///如果新增bit位为1,则说明该节点在新位置,则将它挂到新位置的链表
                        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;
}

HashMap1.8 使用 e.hash & oldCap来计算元素新位置相对于旧位置所新增的比特位。因为容量为 2^n ,所以在二进制上第 n 位为 1 ,其他位为 0 ,通过元素的 hash 与容量按位与,可得到第 n 位的比特位。而元素位置的计算是通过 hash & (n -1)来计算的,所以元素新的位置取决于新增的比特位,如果新增的比特位为 0 ,则说明元素还在原位置,如果新增比特位为 1 ,元素则在新位置(原下标+旧容量)。

例如,当旧容量为 16 时,16-1 对应的二进制 1111 ;新容量为 32 ,32-1 对应的二进制为 11111 。如果 hash 为 11001111001011110 ,则 hash & (16-1) = 1110,hash & (32-1) = 11110,刚好多了 hash & 16 = 10000。

该方法主要实现了:先设置新容量和新阈值,如果是链表,则对链表进行处理。从头开始遍历链表,把新增比特位为 0 的节点放到一个链表,为 1 的放到一个链表,再分别把这两个链表挂到原位置和新位置。这保证了链表顺序不会倒置。

HashMap1.7 与 HashMap1.8 相比,1.7 采用了遍历旧数组,获取到链表。遍历链表,重新计算元素在新数组的位置,以头插法的方式插入到链表,最后会导致了链表顺序会被倒置。

get()方法

根据 key 获取元素的值。该方法比较简单,主要是遍历红黑树或链表,根据 key 找到对应的节点,将值返回。

public V get(Object key) {
    Node<K,V> e;
	//如果存在该key对应的节点,则返回对应的值,否则返回null
    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) {
		//如果桶的第一个节点的key相同,则直接返回该节点
        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);
			//遍历链表,找到key相同的节点
            do {
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    return e;
            } while ((e = e.next) != null);
        }
    }
    return null;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值