Java8 HashMap源码分析

HashMap的特点

存储key-value键值对,允许key,value为空,遍历无序,hashMap不是线程安全的。

类定义

public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable
//实现了Map,Cloneable,Serializable接口
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; //默认初始化容量16
static final int MAXIMUM_CAPACITY = 1 << 30;//最大容量2的30次方
static final float DEFAULT_LOAD_FACTOR = 0.75f;//默认负载因子0.75
static final int TREEIFY_THRESHOLD = 8;//当链表节点数量大于等于8的时候,转为红黑树
static final int MIN_TREEIFY_CAPACITY = 64;//node数组长度要大于等于64才能被树化

构造函数

从构造函数可以看出来,单纯new HashMap出来不使用的话是不怎么占用内存的。

    //不带参数的构造函数只会设置默认的负载因子
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

//构造函数
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;
        //计算阀值,返回大于cap的2的n次方的一个数
        this.threshold = tableSizeFor(initialCapacity);
}


//返回大于cap的2的n次方的一个数
   static final int tableSizeFor(int cap) {
        //保证n的各位都为1,最后再加1就是一个2的n次方的一个数
        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;
    }

put方法

过程描述:

1:首先会检查Node数组是否需要用resize()初始化。默认初始化容量是16。自定义容量就会设置成一个>你设置的容量的2的n次方的一个容量。

2:获取经过扰动函数后返回的哈希值。哈希值对数组取模后定位到对应的哈希桶。情况一还没有节点,就直接设置第一个节点。

如已经存在首节点,就会遍历链表或者红黑树查找是否存在相同的元素(主要是通过哈希值,==内存地址,equals判断),如果不存在相同的元素就添加到链表或者红黑树里去。

3:添加到数据结构里后,会修改元素个数,检查是否需要扩容,如果当前个数>阀值就扩容2倍。同时修改阀值为旧的阀值的2倍。

//存放一个元素
    public V put(K key, V value) {
        //计算key的哈希值
        return putVal(hash(key), key, value, false, true);
    }

    //计算key的哈希值,hash值会和移动到低位的高位进行异或,这里应该是为了更均匀的分布在hash捅里面吧
     static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

    // 存放key value 
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent//缺失才替换,
                   boolean evict // 是否驱逐) {
        // tab存放哈希桶
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        // tab数组没有内容 就重新扩容resize(),
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null) // hash定位tab数组下标,tab[i]没有元素的话就新创建一个节点
            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))))//哈希值一样,如果是同一个key,或者equals相同就说明已经存在了,所以hash函数改了,equals也要改
                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) // 循环8次就会转换会红黑树,转换为红黑树的阀值是8
                            treeifyBin(tab, hash);//转换成红黑树
                        break;
                    }
                    // 之前就已经存在了
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            if (e != null) { // 已经存在旧的值的话
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;//默认这里会进来
                afterNodeAccess(e);//一个空的实现,供扩展
                return oldValue;//返回这个旧的值
            }
        }
        // 插入了志 要把modCount 修改下
        ++modCount;

       //当前元素个数>阀值就扩容
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);//一个空实现,供其他继承类扩展
        return null;
    }

 扩容函数resize()

初始化扩容就是设置默认容量16,阀值设置12。

不是初始化扩容的话,会设置成2倍容量,阀值也变成2倍。如果当前容量超过2的30次方将不再进行扩容。

扩容后需要将旧数组的所有元素迁移到新数组。

 

//resize这个方法
final Node<K,V>[] resize() {
		//保存下table引用
        Node<K,V>[] oldTab = table;
		//oldTab数组的长度
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
		//旧的阀值
        int oldThr = threshold;
		//新的容量,新的阀值
        int newCap, newThr = 0;
        if (oldCap > 0) {
		    //超过2的30次方(大概10亿多)的长度就不扩容了
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
			//容量double,如果tab数组扩容长度没有超过最大限制,newThr就变城双倍oldThr
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
        else if (oldThr > 0) // 初始化容量为旧的阀值
            newCap = oldThr;
        else {               // 如果没有给阀值,那就都用默认16
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);//默认负载因子0.75*默认容量16 = 12
        }
        if (newThr == 0) {//自定义设置了容量,但是没有设置新的阀值,就用当前tab容量*负载因子重新计算下
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
		//重新设置阀值
        threshold = newThr;
		//根据新的容量创建一个新的Node数组
        @SuppressWarnings({"rawtypes","unchecked"})
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
		//如果oldTab不为空,就要迁移到newTab
        if (oldTab != null) {
			//遍历旧的Tab数组下吧
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;//e取oldCap[j]第一个元素
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
                    if (e.next == null)//只有一个节点,直接计算在新数组的index
                        newTab[e.hash & (newCap - 1)] = e;
                    else if (e instanceof TreeNode)//如果是树节点,该捅是一个红黑树了,split后面分析
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    else { // 是一个链表并且不止一个元素
					    //低位头结点,低位尾节点
                        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) {//用这个来判断放在新数组的低位还是高位,哈希值小于oldCap就低位,否则高位,可以拆分原来的链表,更分散链表元素,减少碰撞
                                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;
    }

get操作

	public V get(Object key) {
        Node<K,V> e;
		//主要看getNode方法
        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 &&
		    //hash值对tab长度取模算出 拿出下标对应第一个元素
            (first = tab[(n - 1) & hash]) != null) {
            if (first.hash == hash && // 优先检查是否是第一个元素,是的话就直接返回
                ((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;
    }

//查找目标节点
	final TreeNode<K,V> getTreeNode(int h, Object k) {
        return ((parent != null) ? root() : this).find(h, k, null);
    }
	
	//从根节点开始查找
	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的哈希值就往左边找
                    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;
        }

 remove操作

    public V remove(Object key) {
        Node<K, V> e;
        //主要看removeNode方法
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
                null : e.value;
    }

    public V remove(Object key) {
        Node<K, V> e;
        //主要看removeNode方法
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
                null : e.value;
    }

    final HashMap.Node<K,V> removeNode(int hash, Object key, Object value,
                                       boolean matchValue, boolean movable) {

        HashMap.Node<K,V>[] tab; HashMap.Node<K,V> p; int n, index;

        if ((tab = table) != null && (n = tab.length) > 0 &&
                (p = tab[index = (n - 1) & hash]) != null) {// 哈希桶里面有元素
            //node就是要查找的元素
            HashMap.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 HashMap.TreeNode)
                    node = ((HashMap.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);
                }
            }
            // 找到要删除的元素 && (不需要匹配值 || node的值就是要删除的value || node值equals(value))
            if (node != null && (!matchValue || (v = node.value) == value ||
                    (value != null && value.equals(v)))) {
                if (node instanceof HashMap.TreeNode)
                    ((HashMap.TreeNode<K,V>)node).removeTreeNode(this, tab, movable);//红黑树移除
                else if (node == p)//如果是第一个节点
                    tab[index] = node.next;//直接设置头结点为要删除节点的next节点
                else //执行链表删除,修改p节点(node前置节点)的next引用即可
                    p.next = node.next;
                ++modCount;//修改次数增加,可以用来并发修改异常的检测
                --size;//大小-1
                //扩展接口
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }

clear操作

   public void clear() {
        HashMap.Node<K,V>[] tab;
        modCount++;
        //遍历table数组,将每一个数组里面的内容置空,java gc会自动回收
        if ((tab = table) != null && size > 0) {
            size = 0;
            for (int i = 0; i < tab.length; ++i)
                tab[i] = null;
        }
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值