HashMap原理+源码分析

4 篇文章 0 订阅
4 篇文章 0 订阅

HashMap 原理

和 HashTable 的不同

HashMap 是⾮线程安全的, HashTable 是线程安全的,因为 HashTable 内部的⽅法基本都经过 synchronized 修饰。

HashMap 可以存储 null 的 key 和 value,但 null 作为键只能有⼀个, null 作为值可以有多个; HashTable 不允许有 null 键和 null 值,否则会抛出NullPointerException 。

① 创建时如果不指定容量初始值, Hashtable默认的初始大小为 11,之后每次扩充,容量变为原来的 2n+1。 HashMap 默认的初始化大小为 16。之后每次扩充,容量变为原来的 2 倍。② 创建时如果给定了容量初始值,那么Hashtable 会直接使⽤你给定的大小,而 HashMap 会将其扩充为 2 的幂次方大小。

JDK1.8 以后的 HashMap 在解决哈希冲突时有了较大的变化,当链表长度大于阈值(默认为 8)(将链表转换成红黑树前会判断,如果当前数组的长度小于 64,那么会选择先进行数组扩容,而不是转换为红黑树)时,将链表转化为红黑树,以减少搜索时间。 Hashtable 没有这样的机制。

全局变量与常量
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;

    /**
     * 数组中链表长度大于TREEIFY_THRESHOLD,转红黑树的阈值
     */
    static final int TREEIFY_THRESHOLD = 8;

    /**
     * 当执行resize操作时,当桶中bin的数量少于UNTREEIFY_THRESHOLD时使用链表来代替树。
     */
    static final int UNTREEIFY_THRESHOLD = 6;

    /**
     * 如果容量低于这个值,则优先扩容,而不是树化
     */
    static final int MIN_TREEIFY_CAPACITY = 64;
	/**
     * 位桶数组
     */
	transient Node<K,V>[] table;

    /**
     * KV集合
     */
    transient Set<Map.Entry<K,V>> entrySet;

    /**
     * 表示HashMap中存放KV的数量(为链表和树中的KV的总和)。
     */
    transient int size;


    /**
     * 表示当HashMap的size大于threshold时会执行resize操作。threshold=capacity*loadFactor
     */
    
    int threshold;

    /**
     * 负载因子用来衡量HashMap满的程度。loadFactor的默认值为0.75f。计算HashMap的实时负载因子的方法		 * 为:size/capacity
     */
    final float loadFactor;


	/**
     * 位桶数组的长度
     */
	final int capacity() {
        return (table != null) ? table.length :
            (threshold > 0) ? threshold :
            DEFAULT_INITIAL_CAPACITY;
    }
构造函数
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;
    	//	开始时threshold阈值与capacity相同
        this.threshold = tableSizeFor(initialCapacity);
    }

//	返回大于输入参数且最近的2的整数次幂的数
static final int tableSizeFor(int cap) {
    /**
    * 	右移一位,再或运算,就有两位变为1;

		右移两位,再或运算,就有四位变为1,,,

		最后右移16位再或运算,保证32位的int类型整数最高有效位之后的位都能变为1.
    */
    	//	如果cap刚好为2的整数次幂,这一步则保证值不变
        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;
    }


    /**
     * DEFAULT_LOAD_FACTOR 为初始负载因子0.75
     */
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    /**
     * Constructs an empty <tt>HashMap</tt> with the default initial capacity
     * (16) and the default load factor (0.75).
     */
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }
扰动函数

HashMap 通过 key 的 hashCode 经过扰动函数处理过后得到 hash 值,然后通过 (n - 1) & hash 判断当前元素存放的位置(这⾥的 n 指的是数组的⻓度),如果当前位置存在元素的话,就判断该元素与要存⼊的元素的 hash 值以及 key 是否相同,如果相同的话,直接覆盖,不相同就通过拉链法解决冲突。
所谓扰动函数指的就是 HashMap 的 hash 方法。使用 hash 方法也就是扰动函数是为了防止一些实现比较差的 hashCode() 方法 换句话说使⽤扰动函数之后可以减少碰撞。

/**
JDK1.8:首先将高16位无符号右移16位与低十六位做异或运算。如果不这样做,而是直接做&运算那么高十六位所代表的部分特征就可能被丢失 将高十六位无符号右移之后与低十六位做异或运算使得高十六位的特征与低十六位的特征进行了混合得到的新的数值中就高位与低位的信息都被保留了,而在这里采用异或运算而不采用& ,| 运算的原因是 异或运算能更好的保留各部分的特征,如果采用&运算计算出来的值会向1靠拢,采用|运算计算出来的值会向0靠拢
*/
static final int hash(Object key) {
        int h;
    // key.hashCode():返回散列值也就是hashcode
	// ^ :按位异或
	// >>>:⽆符号右移,忽略符号位,空位都以0补⻬
    
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
/**
JDK1.7:经过四次扰动,性能稍差一点
*/
static int hash(int h) {
	h ^= (h >>> 20) ^ (h >>> 12);
	return h ^ (h >>> 7) ^ (h >>> 4);
}
第一次put()
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,tab和p默认值是null;n是容器数组容器的长度,i用来存数组下标
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        /**
          * table是位桶数组.实际上是一个Node的数组
          *	后半部分不执行.
          */
        if ((tab = table) == null || (n = tab.length) == 0)
			// HashMap的懒加载策略,当执行put操作时检测Table数组初始化。
            n = (tab = resize()).length;	//16
        if ((p = tab[i = (n - 1) & hash]) == null)	// 如果数组这个位置为空,直接把entry放进去
            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) {
                        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;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
    
    
        ++modCount;// 快速报错机制.他是一个成员变量,也记录了HashMap经过结构修改的次数.
        if (++size > threshold)	// 如果长度大于了扩容点.那就进行扩容。
            resize();
        afterNodeInsertion(evict); // 这个方法...不解.因为是一个空方法,注释说是回调LinkedHashMap的后续操作.
        return null;	// 第一次添加元素,返回 null
    }
put()

把前面else里的内容取出

			Node<K,V> e; K k;
//进行值的判断: 判断是不是对于相同的key值传进来不同的value,若是如此,将原来的value进行返回
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
// 如果当前Node类型为TreeNode,调用 PutTreeVal 方法。(红黑树)
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
//如果不是TreeNode,就是链表,遍历并与输入key做命中碰撞。 
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
//如果当前Table中不存在当前key,则添加。
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
//超过了``TREEIFY_THRESHOLD``则转化为红黑树。
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
//做命中碰撞,使用hash、地址和equals同时判断(不同的元素hash可能会一致)。
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
//如果命中不为空,更新操作。
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                //	如果是只添加,那么oldValue必须为null
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
reseize()方法
final Node<K,V>[] resize() {
    	//将当前table暂存到oldtab来操作
        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) {
                //阈值设置为Integer的最大值,远大于默认的最大容量
                threshold = Integer.MAX_VALUE;
                //直接返回当前table,不用扩容
                return oldTab;
            }
            //正常情况下,非初始化
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // 双倍扩大原内存和阈值并赋给新的table
        }
    	//定义了阈值,但没有初始化(有参构造)
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
    	//未定义阈值,未初始化(无参构造),新阈值为默认的12
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
    	//当只满足原阈值大于0的条件时,新阈值等于新容量*默认扩容因子
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
    	//把新的阈值赋给当前table
        threshold = newThr;
        @SuppressWarnings({"rawtypes","unchecked"})
    	//创建容量为newCap的新table
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
        if (oldTab != null) {
            //对原table进行遍历
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                //遍历到的赋给e进行暂存,同时将原table对应项赋值为null
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
                    //该位置只有一个KV
                    if (e.next == null)
			//等于是创建一个新的空table然后重新进行元素的put,这里的table长度是原table的两倍,取决于hash值与newCap上为1的那一位相对应,若为0则位置不变,若为1,则新位置等于原位置加上oldCap
                        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;//用于保存put后不移位的链表
                        Node<K,V> hiHead = null, hiTail = null;//用于保存put后移位的链表
                        Node<K,V> next;
                        do {
                            next = e.next;
//如果与的结果为0,表示不移位,将桶中的头结点添加到lohead和lotail中,往后如果桶中还有不移位的结点,就向tail继续添加
                            if ((e.hash & oldCap) == 0) {
//在后面遍历lohead和lotail保存到table中时,lohead用于保存头结点的位置,lotail用于判断是否到了末尾
                                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) {
                            //尾部元素指向null
                            loTail.next = null;
                            //因为lohead链的位置与扩容前的位置一样,故直接将链表连接到数组上即可
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            //尾部元素指向null
                            hiTail.next = null;
			//扩容后的有的元素的索引位置发生了变化,故直接在索引的位置上加上扩容前容量的数组后边连接链表
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }
get()方法
public V get(Object key) {
        Node<K,V> e;
        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 &&
        //查找需要查找的key在散列表的数组中的位置,并且把当前数组元素赋给first,判断这个位置元素是否为空
        //(n-1) & hash 作用是计算数组索引下标
            (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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值