厉害了,竟然有人把HashMap底层原理讲解的这么清楚!佩服

1,196 阅读9分钟

一、散列表结构

散列表结构就是数组+链表的结构

本文分享给需要面试刷题的朋友,我特意整理了一下,里面的技术不是靠几句话就能讲清楚,多问题其实答案很简单,但是背后的思考和逻辑不简单,要做到知其然还要知其所以然。如果想学习Java工程化、高性能及分布式、深入浅出。性能调优、Spring,MyBatis,Netty源码,数据结构,jvm,多线程等等,由于篇幅有限,以下只展示小部分面试题,有需要完整版的朋友可以点一点链接跳转领取,链接:戳这里免费下载,获取码:掘金

二、什么是哈希?

Hash也称散列、哈希,对应的英文单词Hash,基本原理就是把任意长度的输入,通过Hash算法变成固定长度的输出

这个映射的规则就是对应的哈希算法,而原始数据映射后的二进制就是哈希值

不同的数据它对应的哈希码值是不一样的

哈希算法的效率非常高

三、HashMap原理讲解

3.1继承体系图

3.2Node数据结构分析

static class Node<K,V> implements Map.Entry<K,V> {
    final int hash;计算得到哈希值
    final K key;
    V value;
    Node<K,V> next;
}

interface Entry<K, V> {
        K getKey();
        V getValue();
        V setValue(V value);
 

3.3底层存储结构

当链表长度到达8时,升级成红黑树结构

3.4put数据原理分析

首先put进去一个key----value 根据key值会计算出一个hash值 经过扰动使数据更散列 构造出一个node对象 最后在通过路由算法得出一个对应的index

3.5什么是哈希碰撞?

当传入的数据key对应计算出的hash值的后四位和上一个一样时,这时候计算出的index就会一致,就会发生碰撞,导致数据变成链表

  • 例如: (16-1)------->0000 0000 0000 1111 “张三”------->0100 1101 0001 1011 “李四”-------->1011 1010 0010 1011

此时,就会发现,张三和李四计算出的hash值转化为二进制的后四位一致,导致计算出index一致

3.6JDK8为什么引入红黑树?

哈希碰撞,会带来链化,效率会变低

引入红黑树会提高查找效率

3.7扩容机制 每次扩容为初始容量的2倍

eg:16------->32

为了防止数据过多,导致线性查询,效率变低,扩容使得桶数变多,每条链上数据变少,查询更快

四、手撕源码

1.HashMap核心属性分析

树化阈值-----8和64

负载因子0.75

threshold扩容阈值,当哈希表中的元素超过阈值时,触发扩容

loadFactory负载因子0.75,去计算阈值 eg:16*0.75

size-------当前哈希表中元素个数

modCount--------当前哈希表结构修改次数

2.构造方法分析

public HashMap(int initialCapacity, float loadFactor) {
    //校验 小于0报错
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal initial capacity: " +
                                           initialCapacity);
    //capacity大于最大值取最大值
    if (initialCapacity > MAXIMUM_CAPACITY)
        initialCapacity = MAXIMUM_CAPACITY;
    //负载因子不能小于等于0
    if (loadFactor <= 0 || Float.isNaN(loadFactor))
        throw new IllegalArgumentException("Illegal load factor: " +
                                           loadFactor);
    this.loadFactor = loadFactor;
    //tableSizeFor方法
    this.threshold = tableSizeFor(initialCapacity);
}

---------------------------------------------------------
//传入一个初始容量,默认负载因子0.75
public HashMap(int initialCapacity) {
    this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
---------------------------------------------------------
//无参数,负载因子默认0.75
public HashMap() {
    this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
---------------------------------------------------------
//传入一个map的对象
public HashMap(Map<? extends K, ? extends V> m) {
    this.loadFactor = DEFAULT_LOAD_FACTOR;
    putMapEntries(m, false);
}
 

3.put方法分析

public V put(K key, V value) {
   //返回putVal方法,给key进行了一次rehash
   return putVal(hash(key), key, value, false, true);
}
----------------------------------------------------------
static final int hash(Object key) {
   //让key对应的hash值的高16位也参与运算
  int h;
  return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
----------------------------------------------------------
final V putVal(int hash, K key, V value, boolean  onlyIfAbsent,boolean evict) 
{
   //tab:引用当前HashMap的散列表
   //p:表示当前散列表的元素
   //n:表示散列表数组的长度
   //i:表示路由寻址的结果
   Node<K,V>[] tab; Node<K,V> p; int n, i;
----------------------------------------------------------   	//延迟初始化逻辑,当第一次调用putVal的时候,才去初始化HashMap对象的散列表大小
   if ((tab = table) == null || (n = tab.length) == 0)
       n = (tab = resize()).length;
----------------------------------------------------------
   //寻找找到桶位,且刚好为null,则把k-v封装成node对象放进去
   if ((p = tab[i = (n - 1) & hash]) == null)
       tab[i] = newNode(hash, key, value, null);
----------------------------------------------------------
   else {
     //e:不为null时,找到一个与当前要插入的key-val一致的key对象
     //k:临时的一个key
       Node<K,V> e; K k;
       //表示桶位中的该元素,与你当前插入的元素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 {
           //链表的情况,而且链表的头元素与我们要插入的key不一致
           for (int binCount = 0; ; ++binCount) {
               
               //条件成立,即说明迭代到最后一个链表了,也没找到与你要插入的key一致的node对象
               //说明要加入到链表的最后
               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一样,进行替换,break跳出循环即可
               if (e.hash == hash &&
                   ((k = e.key) == key || (key != null && key.equals(k))))
                   break;
               p = e;
           }
       }
----------------------------------------------------------
   //e不等于null,说明找到了一个与你插入元素完全一致的,进行替换 
   if (e != null) { // existing mapping for key
           V oldValue = e.value;
           if (!onlyIfAbsent || oldValue == null)
               e.value = value;
           afterNodeAccess(e);
           return oldValue;
       }
   }
----------------------------------------------------------
   //modCount:表示散列表结构被修改次数,替换元素不算次数
   ++modCount;
   //插入新元素,size自增,如果自增大于扩容阈值,则触发扩容
   if (++size > threshold)
       resize();
   afterNodeInsertion(evict);
   return null;
}

4.resize()方法分析

//为了解决哈希冲突,影响哈希效率,所以会有扩容机制
----------------------------------------------------------
final Node<K,V>[] resize() {
    //oldTab:引用扩容前的哈希表
    //oldCap:表示扩容前table的数组长度
    //oldThr:表示扩容之前阈值
    //newCap,newThr:扩容后的数组长度大小,以及扩容后下次的阈值
    Node<K,V>[] oldTab = table;
    int oldCap = (oldTab == null) ? 0 : oldTab.length;
    int oldThr = threshold;
    int newCap, newThr = 0;
----------------------------------------------------------
    //条件成立,说明hashmap散列表已经初始化过了,这是一次正常扩容
    if (oldCap > 0) {
        //扩容之前的table数组大小,已经达到了最大阈值后,则不扩容
        //且设置扩容条件为int最大值
        if (oldCap >= MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return oldTab;
        }
----------------------------------------------------------
    //oldCAP左移一位,实现数值翻倍,且赋值给newcap,newcap小于数值最大值限制 且扩容之前阈值>=16
    //这种情况下,则下一次扩容阈值等于当前阈值翻倍
    else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                 oldCap >= DEFAULT_INITIAL_CAPACITY)
            newThr = oldThr << 1; // double threshold
    }
----------------------------------------------------------    //oldCap == 0,说明hashmap散列表为null
   //1.new HashMap(inttCap,loadFactor);
   //2.new HashMap(inttCap);
   //3.new HashMap(map); map有数据
    else if (oldThr > 0) // initial capacity was placed in threshold
        newCap = oldThr;//一定是2的次方数
----------------------------------------------------------
    //oldCap==0,oldThr==0
    //new HashMap();
    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;
    //说明,hashmap本次扩容之前,table不为null
    if (oldTab != null) {
        for (int j = 0; j < oldCap; ++j) {
            Node<K,V> e;//当前node节点
            //说明当前桶位中有数据,但是具体是链表还是红黑树,还是单个数据,不确定
            if ((e = oldTab[j]) != null) {
                //方便jvm GC时回收
                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;
                        //hash--……1 1111
                        //hash--……0 1111
                        //0b 10000
                        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;
}

5.get方法

public V get(Object key) {
    Node<K,V> e;
    return (e = getNode(key)) == null ? null : e.value;
}
----------------------------------------------------------
final Node<K,V> getNode(Object key) {
    Node<K,V>[] tab; //tab:引用当前hashmap的散列表
    Node<K,V> first, e;//first:桶位中的头元素,e:临时node元素
    int n, hash; //n:table数组长度
    K k;
 ---------------------------------------------------------
     if ((tab = table) != null && (n = tab.length) > 0 &&
        (first = tab[(n - 1) & (hash = hash(key))]) != null) {
         //定位出来的桶位元素,就是我们要get的元素
        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;
}

6.remove方法分析

public V remove(Object key) {
    Node<K,V> e;
    return (e = removeNode(hash(key), key, null, false, true)) == null ?
        null : e.value;
}
----------------------------------------------------------
final Node<K,V> removeNode(int hash, Object key, Object value,boolean matchValue, boolean movable) {
    //tab:引用当前HashMap的散列表
    //p:表示当前散列表的元素
    //n:表示散列表数组的长度
    //index:表示路由寻址的结果
        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) {
  //说明路由的桶位是有数据的,需要进行查找操作,且删除  
----------------------------------------------------------   //node:查找到的结果, e:当前node的下一个元素
            Node<K,V> node = null, e; K k; V v;
            //当前桶位中的元素即为要删除的元素
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                node = p;
----------------------------------------------------------   			//当前桶位的元素为红黑树         
            else if ((e = p.next) != null) {
                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 = e;
                    } while ((e = e.next) != null);
                }
            }
----------------------------------------------------------    //判断node不为空的情况,说明按照key找到了要删除的数据        
            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.next = node.next;
                ++modCount;//修改次数自增
                --size;//长度减少
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    } 
    
    
    

7.replace方法分析

@Override
public boolean replace(K key, V oldValue, V newValue) {
    Node<K,V> e; V v;
    if ((e = getNode(key)) != null &&
        ((v = e.value) == oldValue || (v != null && v.equals(oldValue)))) {
        e.value = newValue;
        afterNodeAccess(e);
        return true;
    }
    return false;
}
----------------------------------------------------------
@Override
public V replace(K key, V value) {
    Node<K,V> e;
    if ((e = getNode(key)) != null) {
        V oldValue = e.value;
        e.value = value;
        afterNodeAccess(e);
        return oldValue;
    }
    return null;
}
ll && v.equals(oldValue)))) {
        e.value = newValue;
        afterNodeAccess(e);
        return true;
    }
    return false;
}
----------------------------------------------------------
@Override
public V replace(K key, V value) {
    Node<K,V> e;
    if ((e = getNode(key)) != null) {
        V oldValue = e.value;
        e.value = value;
        afterNodeAccess(e);
        return oldValue;
    }
    return null;
}

本文分享给需要面试刷题的朋友,我特意整理了一下,里面的技术不是靠几句话就能讲清楚,多问题其实答案很简单,但是背后的思考和逻辑不简单,要做到知其然还要知其所以然。如果想学习Java工程化、高性能及分布式、深入浅出。性能调优、Spring,MyBatis,Netty源码,数据结构,jvm,多线程等等,由于篇幅有限,以下只展示小部分面试题,有需要完整版的朋友可以点一点链接跳转领取,链接:戳这里免费下载,获取码:掘金