HashMap源码分析

常量:

  1. 默认初始化长度:
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
  1. 最大容量
static final int MAXIMUM_CAPACITY = 1 << 30;
  1. 扩容因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
  1. 链表转树零界点,链表长度大于8时,转为树结构,这里的临界点是指一个桶中的元素个数
static final int TREEIFY_THRESHOLD = 8;
  1. 树转链表零界点,参考4
static final int UNTREEIFY_THRESHOLD = 6;
  1. 链表转树容量阈值,通常为1(初始化长度DEFAULT_INITIAL_CAPACITY)的4倍。
static final int MIN_TREEIFY_CAPACITY = 64;

链表长度达到临界点8时,不会直接树化,而是需要先判断当前map容量是否到达容量阈值,如果没达到就扩容,关于这一步的操作,源码及官方解释如下:(原谅我蹩脚的翻译

	/**
     * Replaces all linked nodes in bin at index for given hash unless 
     * 在给定hash值所在数组下标的桶替换所有链表结构(改用红黑树替代)
     * table is too small, in which case resizes instead.
     * 数组容量太小,用扩容代替树化
     * 分析:
     * 1.数组容量太小,若直接树化,后续数组容量到达临界点时扩容后又需要树转链表,频繁链表树结构的互转对性能影响很大
     * 2.而MIN_TREEIFY_CAPACITY应是官方指导的,可能会频繁插入,且hash冲突较大的临界值。
     */
     //
    final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
        //node数组的长度是否达到容量阈值,没有则扩容
        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);
        }
    }

内部类

node用来保存map中的每一个键值对,通过next用来保存同一个位桶上下一个链表节点的值,当转化为红黑树时,就改为treeNode存储了。

/**
     * Basic hash bin node, used for most entries.  (See below for
     * TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
     */
static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V 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; }
		//注意,Node的hash是该键值对key和value的hash值进行亦或运算得出的值
        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;
        }
    }

红黑树又称二叉平衡树,除根节点外,每一个节点都有可能连接着三个节点
普通二叉树:第一个元素为根节点,插入元素,与根节点比较,小于根节点放左边,大于根节点放右边,红黑树是加强版的二叉树,因为二叉树固定根节点的插入很容易导致树的某一侧元素数量远远大于另一侧,红黑树会在每次插入数据时重新计算根节点的位置,尽量使根节点两侧元素分布均匀。
具体算法自行百度。。

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;
        TreeNode(int hash, K key, V val, Node<K,V> next) {
            super(hash, key, val, next);
        }

        /**
         * Returns root of tree containing this node.
         * 红黑树根节点
         */
        final TreeNode<K,V> root() {
            for (TreeNode<K,V> r = this, p;;) {
                if ((p = r.parent) == null)
                    return r;
                r = p;
            }
        }
        //以下省略,有机会重开一章细说
      }

成员变量

transient Node<K,V>[] table;//hashMap的底层数组

transient Set<Map.Entry<K,V>> entrySet;//

/* 
*表示使用迭代器遍历过程中结构修改的次数
*这是jdk在面对迭代遍历的时候为了避免不确定性而采取的快速失败原则。
*/
transient int modCount;

比较重要的成员变量:

//The number of key-value mappings contained in this map.
transient int size;
/**
     * The next size value at which to resize (capacity * load factor).
     *hashMap扩容临界值,hashMap是在插入值之后进行扩容,
     *如果插入某值之后当前容量大于capacity * load factor,则调用resize方法进行扩容,在此之后若没有继续插入数值,则会造成无效扩容
     */
int threshold;
/**
     * The load factor for the hash table.
     * 扩容因子,0.75
     *  = DEFAULT_LOAD_FACTOR
     */
    final float loadFactor;
在这里插入代码片

方法:

hash

  1. 计算key的hash值:取key本身的hash值与其右移16位后的值经过亦或运算后的值
    原因写在个人分析里
    ^运算:同0则0,有1则1,贯穿hashMap整个算法,记住这里亦或运算的特性,后面要用
static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
  1. 静态方法comparableClassFor与compareComparables略,后续补上;
  2. putMapEntries先省略

tabSizeFor

  1. 可以通过构造方法指定hashMap的初始化容量,我们知道,hashMap的容量必须是2的倍数,而传入的值可能不会遵循此标准,故需要根据传入的值重新计算初始化容量。
    以下用了非常巧妙的算法,先减一是因为如果传入的值刚好是2的倍数,那么经过计算之后的值会是传入值的两倍,占用不必要的内存。
    以下用17,也就是00000000 000010001 为例,扩容的最总结果为32
    同时也可以看出,以下运算,通过位移运算与或运算相结合 ,将当前cap -1 的最高位及其右边所有位全部补1。那么+1就会生成最相近的2的倍数了,而且位移运算与或运算的开销都很小,几乎无开销的实现容量的计算。
static final int tableSizeFor(int cap) {
		//00000000 00010000
        int n = cap - 1;
        //00000000 00001000 | 00000000 00010000
        //00000000 00011000
        n |= n >>> 1;
        //00000000 00001100 | 00000000 00011000
        //00000000 00011100
        n |= n >>> 2;
        //00000000 00001110 | 00000000 00011100
        //00000000 00011110
        n |= n >>> 4;
        //00000000 0001111 | 00000000 00011111
        //00000000 00011111
        n |= n >>> 8;
        //00000000 00011111
        n |= n >>> 16;
        //00000000 00011111 + 1
        //00000000 00100000 = 2^5 = 32   
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }

简单常用方法合集

  1. 一些简单的方法:
public int size() {
        return size;
    }
//所以hashMap的isEmpty方法和List的isEmpty方法一样,判断的是已初始化的map是否是空map,若map未初始化,则报空指针
public boolean isEmpty() {
        return size == 0;
    }
    

hashMap是可以保存一个空key空value的,所以使用get方法返回null可能是该key不存在,也有可能是该key对应的值是null,需要判断是否存在key需要通过containsKey方法

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;
    }

根据key的hash值和key获取该key对应位桶上的node链表

/**
     * Implements Map.get and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @return the node, or null if none
     */
    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) {
            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;
    }

put,putVal

  1. 往hashMap存入键值对
public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
final V putVal(int hash,//key的hash值,注意,这里的hash值是key的hashCode与hashCode的高位(右移16位)亦或运算得到的hash值
				 K key, 
				 V value,
				  boolean onlyIfAbsent,//若key与已存在,是否用新值覆盖旧值
                   boolean evict//false表示在创建hashMap时调用此函数,如通过构造方法创建,true表示在构建hashMap之后才调用该方法
                   ) {
        Node<K,V>[] tab;//将成员table赋值给局部变量
         Node<K,V> p;//当前key所在位桶的第一个Node
          int n, i;//n为tab长度,i为当前key对应位桶的下标
        if ((tab = table) == null || (n = tab.length) == 0)
        	//当前map为空时,先扩容
            n = (tab = resize()).length;
            //i = (n - 1) & hash
            //计算下标方式,
        if ((p = tab[i = (n - 1) & hash]) == null)
        	//当前key所在位桶为空,创建新的Node
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e;//根据当前key构建的node
             K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                //p的key等于当前传入key,则根据onlyIfAbsent判断是否需要用新val覆盖原val
                e = p;
            else if (p instanceof TreeNode)
            //p为红黑树结构,这里还没看过
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
            	//循环当前位桶的链表,找到当前key,若没有,则在链表最后插入,binCount代表循环次数,也代表当前链表长度
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        //链表长度大于等于树化阈值,treeifyBin方法树化或扩容
                        //注意:binCount是从0开始,所以是与TREEIFY_THRESHOLD - 1比较
                        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;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

resize

final Node<K,V>[] resize() {
		//扩容前node数组
        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;
            }
            //原容量*2仍小于最大容量,原容量大于默认初始化长度
            //扩容:容量*2,临界值 = cap*loadFactory = 原临界值*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"})
            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;
                            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;
    }

个人分析:

  1. hashMap初始长度默认为16,扩容因子0.75,每次扩容长度均为原数组长度*2.初始化时可以指定初始化长度和扩容因子,初始化长度会通过内部计算转化为 >=传入值 的2的次幂。
  2. hashmap底层是数组加链表的结构,1.8之后引入了红黑树结构,当链表长度大于树化阈值(默认8)时,该桶的链表结构转化为红黑树结构(当前容量小于最小树化容量MIN_TREEIFY_CAPACITY,也就是64时,选择扩容而不是树化,详见hashmap的treeifyBin方法),
  3. hash值的算法:1.7中,hash值的算法比1.8复杂,1.7的hash值为key的hashcode与其经过多次位移运算之后的值进行亦或运算得到的值,这是为了让高位参与运算,使hashmap中的元素更加散列分布,更加均匀的分布在数组上,增加get方法查询的效率,(链表结构的特点,增删快,查询慢),1.8引入了红黑树结构,优化了查询速率,故计算hash值时,只简单的让高位参与运算,来增加散列,没有像1.7那样进行多次位移亦或运算。return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
  4. 数组下标的计算方式:(n-1)&hash,
    面试题:为什么map数组的长度是2的次幂?
    这和数组的下标有关,map是数据加链表的结构,数组结构查询快增删慢,链表结构查询慢增删快,为了使插入map中的元素均匀分布在数组中,需要想办法通过数组的下标计算方式着手,减少hash冲突。hashMap中计算数组下标用的是(n-1)&hash,&运算的特点是,同1则1,所以需要放大不同key的hash值的差异,n-1对数组下标的影响应尽量减低,所以应n-1的二进制每位均为1,所以相应数组长度为2的次幂。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值