HashMap的源码解析

看了不少的hashmap解析源码的文章,然后自己也想总结记录一下,很久就想抽点时间写一篇关于hashmap的文章了,但现实就是不允许,原因有很多,主要还是太菜了,哈哈,现在终于有时间写了。

这篇文章分为hashmap1.7和1.8的解析,自己也不知道怎么开头,也是想到什么写什么,文章顺序可能会有点乱,望各位谅解。现在是北京时间:2019年4月2日 01:30:19。

HashMap1.7解析

首先看看一张图片来了解下HashMap的结构把

在这里插入图片描述
简单说下hashmap的数据结构把。
数组+链表
数组在知道下标之后查询速度尤其快,O(1)的时间复杂度。
链表在增删的时候速度非常快,找到位置后(前提),处理只需要O(1)的时间复杂度,因为不需要移动数据的位置,只需要更改指向的地址即可。但是链表在遍历对比的时候非常慢,时间复杂度为O(n),当然,我觉得这里的链表主要还是用来做哈希冲突时的解决方法,也称为拉链法。

//默认初始化化容量,即16  
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; 

//最大容量,即2的30次方  
static final int MAXIMUM_CAPACITY = 1 << 30;  

//默认装载因子  
static final float DEFAULT_LOAD_FACTOR = 0.75f;  

//HashMap内部的存储结构是一个数组,此处数组为空,即没有初始化之前的状态  
static final Entry<?,?>[] EMPTY_TABLE = {};  

//空的存储实体  
transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;  

//实际存储的key-value键值对的个数
transient int size;

//阈值,当table == {}时,该值为初始容量(初始容量默认为16);当table被填充了,也就是为table分配内存空间后,threshold一般为 capacity*loadFactory。HashMap在进行扩容时需要参考threshold
int threshold;

//负载因子,代表了table的填充度有多少,默认是0.75
final float loadFactor;

//用于快速失败,由于HashMap非线程安全,在对HashMap进行迭代时,如果期间其他线程的参与导致HashMap的结构发生变化了(比如put,remove等操作),需要抛出异常ConcurrentModificationException
transient int modCount;

//默认的threshold值  
static final int ALTERNATIVE_HASHING_THRESHOLD_DEFAULT = Integer.MAX_VALUE;

PUT的过程分析

public V put(K key, V value) {
    // 当插入第一个元素的时候,需要先初始化数组大小
    if (table == EMPTY_TABLE) {
        inflateTable(threshold);
    }
    // 如果 key 为 null,最终会将这个 entry 放到 table[0] 中
    if (key == null)
        return putForNullKey(value);
    // 1. 计算key 的 hash 值
    int hash = hash(key);
    // 2. 找到对应的数组下标
    int i = indexFor(hash, table.length);
    // 3. 遍历一下对应下标处的链表,看是否有重复的 key 已经存在,如果有,直接覆盖,put 方法返回旧值就结束了。
    for (Entry<K,V> e = table[i]; e != null; e = e.next) {
        Object k;
        if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
            V oldValue = e.value;
            e.value = value;
            e.recordAccess(this);
            return oldValue;
        }
    }

    modCount++;
    // 4. 不存在重复的 key,将此 entry 添加到链表中。
    addEntry(hash, key, value, i);
    return null;
}

数组初始化

private void inflateTable(int toSize) {
    // 比如这样初始化:new HashMap(20),那么处理成初始数组大小是 32,保证数组的长度是2的n次方
    int capacity = roundUpToPowerOf2(toSize);
    // 计算扩容阈值:capacity * loadFactor
    threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
    // 初始化数组
    table = new Entry[capacity];
    initHashSeedAsNeeded(capacity); 
}

这里有个小问题,无论是1.7还是1.8的hashmap都是要将数组的大小初始化为2的n次方,该问题留在后面讲。。

计算该key在数组的位置

static int indexFor(int hash, int length) {
	//hash是key的hash值,length为数组长度。
    return hash & (length-1);
}

其实这里有个小问题,有些面试官也会问到,hash % length和 hash & (hash - 1)为什么不直接模 ,而要减一取余?是因为那样计算相对于模的话效率更高一点。各位可以自行测试,我在这里就不举例了。

添加节点到链表中

void addEntry(int hash, K key, V value, int bucketIndex) {
    // 如果当前 HashMap 大小已经达到了阈值,并且新值要插入的数组位置已经有元素了,那么要扩容
    if ((size >= threshold) && (null != table[bucketIndex])) {
        // 扩容
        resize(2 * table.length);
        // 扩容以后,需要重新计算 hash 值
        hash = (null != key) ? hash(key) : 0;
        // 重新计算扩容后的新的下标
        bucketIndex = indexFor(hash, table.length);
    }
    createEntry(hash, key, value, bucketIndex);
}
// 将新值放到链表的表头,然后 size++
void createEntry(int hash, K key, V value, int bucketIndex) {
    Entry<K,V> e = table[bucketIndex];
    table[bucketIndex] = new Entry<>(hash, key, value, e);
    size++;
}

这个方法的主要是先判断是否需要扩容,需要的话先扩容,然后再将这个新的数据插入到扩容后的数组的相应位置处的链表的表头。

数组扩容

void resize(int newCapacity) {
    Entry[] oldTable = table;
    int oldCapacity = oldTable.length;
    if (oldCapacity == MAXIMUM_CAPACITY) {
        threshold = Integer.MAX_VALUE;
        return;
    }
    // 创建新的数组
    Entry[] newTable = new Entry[newCapacity];
    // 将原来数组中的数组移到新的数组当中
    transfer(newTable, initHashSeedAsNeeded(newCapacity));
    table = newTable;
    threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
}

以上是put的一些分析解读,接下来是put的。

put过程分析

public V get(K key) {
    if (key == null)
        return getForNullKey();
        //主要是getEntry方法
    Entry<K,V> entry = getEntry(key);
    return null == entry ? null : entry.getValue();
}

getEntry方法解读

final Entry<K,V> getEntry(K key) {
	//1. 先判断数组的长度
    if (size == 0) {
        return null;
    }
    //2. 计算key的hash值
    int hash = (key == null) ? 0 : hash(key);
    // 3. 通过hash值获取数组下标,然后遍历该下标下的每一个链表节点。
    for (Entry<K,V> e = table[indexFor(hash, table.length)]; e != null;e = e.next) {
        Object k;
        //4. 判断key的hash值与该节点的key的hash值是否相等。判断该节点的key和传进来的key值是否相等。
        if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))
        //5. 如果都相等,返回该节点下的value
            return e;
    }
    return null;
}
1.7的粗略简单的分析这么多,主要是分析1.8的,不知道写下去会留下多少坑,现在是北京时间2019年4月2日 02:15:25,目前还没猝死,继续写。
由于本人技术太菜,1.8的hashmap红黑树部分并没有进行过多的分析,所以就不写红黑树这块的逻辑了,还是要回去多修炼一下啊。。。。

HashMap1.8解析

1.8主要引入了红黑树,当链表到达一定长度时,转换为红黑树存储
在这里插入图片描述

贴下1.8的一些属性

	//初始化默认数组容量 16
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
    
	//数组最大的容量,因为2的30次方是最接近Int的最大数值,我记得31的话就是负数,是多少的话请自行百度。
    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;
	//在转变为树之前,还有一次判断,只有键值对数量大于64时才会转为树,这是为了避免在hash表建立初期,多个键值对恰巧放在同一个链表当中导致不必要的转化
    static final int MIN_TREEIFY_CAPACITY = 64;

开始对以下代码一顿分析

public class Test {
  public static void main(String[] args) {
        Map<String,String> hashMap = new HashMap<>(16);
        hashMap.put("name","yip");
   }
}

首先执行第一条构造参数啦

	//主要分析这个构造参数
    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);
    }


    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

 
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

看下tableSizeFor的源码先分析

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

一开始我看的时候也是一脸懵逼,最后还是百度自己测试一下这个方法。
原来,我们在传入第一个构造参数指定长度的时候,无论是奇数还是偶数,经过这个方法调用后都会生成一个离该数最近的2次方,比如我们传个17进去,就会return 个32出来。为什么是2的次方的,上面1.7也说到了,这里先留个坑,后面解答。

你以为执行完构造函数hashmap就初始化了吗?那你就大错特错了!!真正初始化的是进行put操作,先贴源码。

public V put(K key, V value) {
	//第三个参数 onlyIfAbsent 如果是 true,那么只有在不存在该 key 时才会进行 put 操作
	//第四个参数  evict参数用于LinkedHashMap中的尾部操作,这里没有实际意义
        return putVal(hash(key), key, value, false, true);
    }

putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict)方法

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        //如果第一次进行存放数据,先进行初始化,table 被延迟到进行数据存放时才初始化,触发resize()扩容方法,后面讲。
        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;
            //判断该位置的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);
                        //判断新插入的值是否为链表长度中的第八个,如果是,转换为红黑树
                        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;
                }
            }
            //返回旧的值
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        //如果 HashMap 由于新插入这个值导致 size 已经超过了阈值,需要进行扩容
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

操作过程

  1. 判断数组是否为null,为null进行扩容。
  2. 通过key计算hash值对应下标的地址是否为空,如果为空,直接插入该值。
  3. 判断该链头与传进来的键是否相等,相等直接覆盖值。
  4. 否则判断该节点是否为红黑树,是的话直接调用putTreeVal方法插入键值对。
  5. 不是红黑树即是链表,调用newNode插入值。
  6. 判断新插入的值是否为链表长度中的第八个,如果是,转为红黑树。

扩容操作 resize(),贴上源码分析

HashMap的容量超过当前数组长度(DEFAULTINITIALCAPACITY) * 加载因子(DEFAULTLOADFACTOR),就会执行resize()算法。假设初始长度为16,加载因子默认为0.75, 16 * 0.75=12,当HashMap容量超过12时,就会执行扩容操作。长度是原来的两倍(旧的长度左移一位),并且将原来的HashMap数组的节点转换到新的数组。

    final Node<K,V>[] resize() {
     	//定义旧的数组为 Node 类型的数组,oldTab
        Node<K,V>[] oldTab = table;
        
        // 如果oldTab==null  则返回 0,否则返回数组大小
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        
		// 说明已经不是第一次扩容,已经初始化过,容量一定是2的n次方,所以可以直接位运算
        if (oldCap > 0) {

		// 超过最大值不会进行扩容,并且把阈值设置成Interger.MAX_VALUE
            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
        }

		//对应使用 new HashMap(int initialCapacity) 初始化后,第一次 put 的时候
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;

		//对应使用 new HashMap() 初始化后,第一次 put 的时候
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }

	   //如果newThr还没有被赋值,那么就根据newCap计算出阈值
        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];
            
		// 如果是初始化数组,到这里就结束了,返回 newTab 即可
        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);

					// 如果不是树,只是链表,即长度还没有大于 8 进化成树
                    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;

						//这是是真尼玛难懂,将它和原来的长度进行相与,就是判断他的原来的hash的上一个 
						//将每个元素和原来数组长度进行与运算,判断是否为0,如果为0,那么索引位置不变,如果不为0,那么索引位置等于原来的索引+原来数组的长度 
                            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;
    }

以上是我觉得hashmap最重要的两个方法了吧,接下来在简单的分析下get方法

 public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

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

填坑了,为什么hashmap的长度是2的n次方

是因为hashmap为了存取高效尽量的减少hash碰撞,尽量的把数据分配的均匀。
详情可看添加链接描述

最后贴一张put流程图

在这里插入图片描述

以后再写hashmap的线程安全问题,今天就写到这里,睡了。狗命重要。2019年4月2日 04:03:48

猜你喜欢

转载自blog.csdn.net/weixin_41649090/article/details/88960992
今日推荐