HashMap源码解析(jdk1.8)

HashMap简介

java.util.HashMap实现了java.util.Map接口,是存储key、value的一种数据结构。key 和value都可以为null,但是key不可以重复,若是重复则会覆盖。

jdk1.7中,HashMap是数组+链表实现的;
jdk1.8中,HashMap是数组+链表+红黑树实现的。

下面主要介绍jdk1.8的Hash源码。

原理

  • HashMap中首先有个Node数组存储数据,然后根据hash算法算出key的hash值,并通过(n - 1) & hash算出数组的索引,使这个key对应的值存储到数组的索引位置中。
  • 如果出现hash冲突,在原来的基础上延伸链表存储数据。
  • 如果延伸出的链表过长,则转为红黑树降低树的高度,增加查询效率。
  • 如果数组的大小达到扩容的阈值,则扩容数组并迁移数据到扩容后的数组中。

数组加链表的形式
在这里插入图片描述
链表过长,转为红黑树
在这里插入图片描述

源码分析

基本属性

//默认的初始化容量(Node数组的大小)
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
//最大容量(Node数组的大小)
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;
//存储数据的Node数组
transient Node<K,V>[] table;
//key、value的集合,用于遍历Map
transient Set<Map.Entry<K,V>> entrySet;
//map大小,也就是存了多少个数据
transient int size;
//map修改次数
transient int modCount;
//阈值(扩容阈值,达到这个值时,Node数组需要扩容)
int threshold;
//负载因子,扩容阈值的的其中一个算法是DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY,因此负载因子决定扩容的频率
final float loadFactor;

构造方法

//无参的构造方法,负载因子默认0.75f,初始化大小是16
public HashMap() {
       this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
//带初始化大小的构造方法,负载因子默认值是0.75f,初始化大小是16
public HashMap(int initialCapacity) {
    this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
//带初始化大小、负载因子的构造方法
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);
}
//根据传入的map生成一个新map
public HashMap(Map<? extends K, ? extends V> m) {
    this.loadFactor = DEFAULT_LOAD_FACTOR;
    putMapEntries(m, false);
}

查找

java.util.HashMap#getNode
HashMap中数据是存在Node数组中,就是Node<K,V>[] table。如果出现Hash冲突就会在数组的这个位置延伸出链表。Node<K,V>中存的是key、value。
下面的方法是先获取Node,如果Node为空,则返回null,否则返回Node.value。

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

java.util.HashMap#getNode
根据key和hash值获取Node,Node里存储的是key、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 &&
        (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;//这种情况是未产生hash冲突,数组key对应的位置存的Node就是想要的数据
        if ((e = first.next) != null) {//产生hash冲突,key对应的数组位置可能有多个数据,遍历延伸出的链表获取数据
            if (first instanceof TreeNode)//如果是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;
}

下面的方法是根据key的hash值,定位到数组的某个位置。
根据key取hash值,是为了数 值更离散。
tab[(n - 1) & hash]是为了让该值落到数组的某个位置,比如数组长度是16,15&hash的值取值范围是0-15,这样根据key就会定位到数组的某个位置。

first = tab[(n - 1) & hash]

插入

map.put(“a”,“aa”);
put方法,把key、value放到map中。

java.util.HashMap#put

public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

插入方法

java.util.HashMap#putVal的几个入参:

  • int hash :key的hash值
  • K key :key值,泛型
  • V value :value值,泛型
  • boolean onlyIfAbsent :如果为true,不改变已存在的值。
  • boolean evict:如果为false,存储值的数组正在创建中。
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    if ((tab = table) == null || (n = tab.length) == 0)
    	//相当于map是空的,Node数组是空的,因此需要创建或扩容Node数组。
    	//resize方法是扩容
        n = (tab = resize()).length;
    if ((p = tab[i = (n - 1) & hash]) == null)
    	//该key对应Node数组中的位置为空,需要创建一个Node
        tab[i] = newNode(hash, key, value, null);
    else {//该key对应Node数组中的位置有Node
        Node<K,V> e; K k;
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))//该Node就对应着传入的key,直接取该Node
            e = p;
        else if (p instanceof TreeNode)//红黑树的处理逻辑 
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        else {//有hash冲突,需要遍历链表
            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
                        //转为红黑树,TREEIFY_THRESHOLD是链表过长转为红黑树的阈值
                        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。找到了这个key对应的Node
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);//空实现,等待扩展
            return oldValue;//返回旧值
        }
    }
    ++modCount;//改变Map次数加1
    if (++size > threshold)//map的大小加1,同时大于扩容的阈值
        resize();//扩容
    afterNodeInsertion(evict);//空实现,等待扩展
    return null;
}

插入方法总结:

  • 先判断Node数组是否为空,为空则扩容数组;
  • 根据key找到Node数组中对应位置的Node。Node为空则创建Node放到该位置;
  • 如果Node不为空,判断该Node是否为该key对应的Node(多个key可能在Node数组的同一个位置,hash冲突导致的),若是则将该Node赋值给临时变量e;
  • 如果Node不为空且该Node是TreeNode类型,走红黑树逻辑放入数据。
  • 如果Node不为空且不是上面两种场景,说明是Node数组中该位置延伸出来的链表,遍历链表判断是否为该key对应的Node,是则放入数据返回Node,否则继续遍历,直到遍历到末尾也没找到Node就创建Node放入数据(期间如果达到树化阈值,则将链表转为红黑树);
  • 如果该key已经存在,则获取key的值并直接返回;
  • 修改次数加1;
  • map大小加1;
  • 如果达到map扩容阈值,执行扩容逻辑;
  • 该key不存在,返回null;

扩容方法

java.util.HashMap#resize

final Node<K,V>[] resize() {
		//扩容前的Node数组
        Node<K,V>[] oldTab = table;
        //扩容前的Node数组大小
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        //扩容前的扩容阈值
        int oldThr = threshold;
        //声明扩容后Node数组的大小及扩容阈值
        int newCap, newThr = 0;
        if (oldCap > 0) {//Node数组已经被初始化
            if (oldCap >= MAXIMUM_CAPACITY) {//已达到Node数组的最大值,不需要再扩容
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)//按旧容量和阈值的2倍计算新容量和阈值的大小
                newThr = oldThr << 1; // double threshold,阈值*2
        }
        else if (oldThr > 0) // initial capacity was placed in threshold
            //调用 HashMap(int) 和 HashMap(int, float) 构造方法时会产生这种情况,此种情况下 newCap = oldThr,newThr 在第二个条件分支中算出
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults
        	//调用 HashMap() 构造方法会产生这种情况。
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        if (newThr == 0) {// 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数组
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;//赋值新的Node数组给HashMap
        if (oldTab != null) {//之前HashMap中有数据
            for (int j = 0; j < oldCap; ++j) {//遍历原来的Node数组,准备迁移数据到扩容后的Node数组中
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {//Node数组的第j个元素有数据
                    //将该数组中该位置元素情况方便垃圾回收
                    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 {//这是(原来的位置+oldCap)那组
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
						//下面的两个if将链表头放到扩容后数组的指定位置,这样数据就迁移过来了
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;//返回扩容后的Node数组
    }

扩容方法总结:

  • 计算扩容后的Node数组容量、及扩容阈值。
  • 如果扩容前的Node数组为空,说明没数据,不需要迁移。直接返回扩容后的Node数组。
  • 遍历扩容前的数组,准备迁移数据。
  • 如果数组中该位置为空,说明没有数据,继续下一个循环。
  • 如果数组中该位置有值,且该元素的next元素为空,说明未产生hash冲突,没有延伸出链表及红黑树,直接根据key、hash映射到新数组的指定位置即可。
  • 如果数组中该位置有值,且该元素的next元素是TreeNode,说明该数组位置延伸出红黑树,需要对红黑树进行拆分并重新映射到新数组中。
  • 除了上面两个场景以外,就是链表。遍历链表进行数据迁移。
  • 遍历链表时,通过条件if(e.hash & oldCap) == 0)对链表中的数据进行分组。e.hash&oldCap==0说明该数据在数组原来的索引位置,否则该数据在(数组原来的索引位置+oldCap)的位置。这样就分成两组,分出两个链表。
  • 将两个链表放到新数组中的两个位置。
  • 返回新数组,resize()方法结束。

删除

java.util.HashMap#remove(java.lang.Object)

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

java.util.HashMap#removeNode

final Node<K,V> removeNode(int hash, Object key, Object value,
                            boolean matchValue, boolean movable) {
     Node<K,V>[] tab; Node<K,V> p; int n, index;
     if ((tab = table) != null && (n = tab.length) > 0 &&
         (p = tab[index = (n - 1) & hash]) != null) {
         //定位该key对应Node数组中的位置,如果为空返回null
         Node<K,V> node = null, e; K k; V v;
         if (p.hash == hash &&
             ((k = p.key) == key || (key != null && key.equals(k))))//数组中的Node直接是想要的数据,未产生hash冲突,未生成链表及红黑树
             node = p;
         else if ((e = p.next) != null) {//有hash冲突,生成了链表或红黑树
             if (p instanceof TreeNode)//红黑树的处理逻辑
                 node = ((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是node的前一个节点
                     p = e;
                 } while ((e = e.next) != null);
             }
         }
         if (node != null && (!matchValue || (v = node.value) == value ||
                              (value != null && value.equals(v)))) {//删除数据
             if (node instanceof TreeNode)//红黑树的删除逻辑
                 ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
             else if (node == p)//没有产生链表及红黑树的场景
                 tab[index] = node.next;
             else
             	//链表处理逻辑。根据上面循环链表的处理,p是node的上一个节点。
                 p.next = node.next;
             ++modCount;//修改次数加1
             --size;//map大小加1
             afterNodeRemoval(node);
             return node;//返回删除的节点
         }
     }
     return null;
 }

上面的代码均已注释且逻辑简单,就不总结了。

  • 21
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值