hashmap源码分析

hashmap的源码分析,基于jdk8,关于树的方法,不展开

1、hashmap的一些属性

//默认容量,位运算
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
//最大容量,位运算
static final int MAXIMUM_CAPACITY = 1 << 30;
//默认负载因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//链表转树界限
static final int TREEIFY_THRESHOLD = 8;
//树转链表界限
static final int UNTREEIFY_THRESHOLD = 6;
//链表转树的容量最小限制
static final int MIN_TREEIFY_CAPACITY = 64;
//hashmap的数组,1.8的hashmap是数组+链表和红黑树的结构,每个数组元素保存链表的头节点或者红黑树的根节点
transient Node<K,V>[] table;

transient int size;

int threshold;
//负载因子
final float loadFactor;

2、构造方法

//无参构造方法,将负载因子设为默认的负载因子,初始化hashmap不在这里,在put方法
	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;
        this.threshold = tableSizeFor(initialCapacity);//保证容量是2的幂
    }
	public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

3、容量控制方法

//控制容量是2的幂
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;
}

4、put方法

//计算key的hash,并调用真实设值方法
	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) {
		//hashmap的临时变量
        Node<K,V>[] tab; Node<K,V> p; 
		//n,数组长度;i,key在数组的下标
		int n, i;
		//如果hashmap没有初始化则初始化
        if ((tab = table) == null || (n = tab.length) == 0)
            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 {
				//遍历链表,直到找到链表末端,将Node放入链表末端,判断是否是否应该树化
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
			//覆盖原来Node的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);
        return null;
    }
	
	static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

5、树化方法

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();
        //树化,不展开
        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);
        }
    }

6、扩容方法

final Node<K,V>[] resize() {
		//保存到临时变量
        Node<K,V>[] oldTab = table;
		//旧的容量
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        //旧的扩容阈值
		int oldThr = threshold;
		//新的容量,新的扩容阈值
        int newCap, newThr = 0;
		//hashmap不为空
        if (oldCap > 0) {
			//如果容量已达上限,将扩容阈值设为比容量上限更大的值,避免再扩容
            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
            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"})
		//初始化一个新的空数组 容量原来的两倍,为扩容后的hashmap数据结构
            Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
		//hashmap原来有值,进行扩容
        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;
							//将链表才分为两个链表,下面分析
                            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;
    }

7、get方法

//计算hash并调用getNode方法
public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }
//真正执行get的方法
final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
		//hashmap的数组初始化了并且hash对应数组下标有值
        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;
    }

8、hashmap的Node

//Node,静态内部类
static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;//node的hash
        final K key;//Node的key值
        V value;//Node的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;
        }
    }

9、链表的拆分原理

链表的拆分根据Node的hash进行拆分,hash按位与就数组容量,为0,放在低链,不为0,放在高链
比如旧的容量是16,新的容量是32
旧的容量的二进制是 00000000 000000000 00000000 00010000
Node1的hash是xxxxxxxx xxxxxxxx xxxxxxxx xxx01xxx
按位与后的结果 00000000 00000000 00000000 00000000 为0
Node2的hash是xxxxxxxx xxxxxxxx xxxxxxxx xxx11xxx
按位与后的结果 00000000 00000000 00000000 00010000 不为0
但是这两个在旧的hashmap的数组存放数据时计算hash是和(旧容量-1)按位与,结果是一样的
(旧容量-1) = 16-1 = 15 = 00000000 00000000 00000000 00001111
Node1和(旧容量-1)按位与结果是 00000000 00000000 00000000 00001000
Node2和(旧容量-1)按位与结果是 00000000 00000000 00000000 00001000
因此这两个都会放在相同的数组位置

10、图解

在这里插入图片描述

11、hashmap的put操作流程

1)、如果hashmap没有初始化,则进行初始化
2)、对key求hash然后计算下标
3)、如果数组下标没有元素,则直接放入数组下标
4)、如果数组下标有元素,则以链表形式放入下标
5)、如果链表长度达到阈值(8),则将链表转化为红黑树(容量需要达到64,否则进行扩容)
6)、如果达到扩容阈值,就扩容

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值