java8 hashMap 底层原理

hashMap 底层的数据结构就是哈希表
jdk1.7 底层就是: 数组+链表,并且插入链表采用头部插入法
jdk1.8 底层结构为: 数组+链表+红黑树(源码中数组长度大于64且链表长度大于8 就把链表转成红黑树,链表长度小于6就把红黑树转成链表),插入链表采用尾部插入法(因为要遍历链表,所以直接插入尾部)
hashmap 非线程安全,1.7和1.8在某种情况下都会出现死循环,多线程情况下使用concurrentHashMap

下面看下源码:
源码分析一:关键属性

 //默认hashmap初始化容量为16
 static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
//最大容量
  static final int MAXIMUM_CAPACITY = 1 << 30;
  // 默认加载因子为0.75,当数组槽位大于0.75时,会2倍扩容
   static final float DEFAULT_LOAD_FACTOR = 0.75f;
     //链表长度大于等于8就转成红黑树(源码中还要满足条件数组     长度大于64)
    static final int TREEIFY_THRESHOLD = 8;
    //链表长度小于等于6就把红黑树结构转成链表
    static final int UNTREEIFY_THRESHOLD = 6;
   //转成红黑树数组大小至少为64
    static final int MIN_TREEIFY_CAPACITY = 64;
    //存储元素的实体数组
    transient Node<K,V>[] table;
    transient Set<Map.Entry<K,V>> entrySet;
    //map中存放元素的个数
    transient int size;

  //被修改的次数
  transient int modCount;
   //临界值   当实际大小超过临界值时,会进行扩容threshold = 加载因子*容量
 int threshold;
/加载因子
 final float loadFactor;

源码分析二: 构造方法

//构造空map,容量默认为16 ,加载因子默认为0.75
HashMap()
//设定数组初始容量和加载因子
HashMap(int initialCapacity, float loadFactor)
//设定初始容量,默认加载因子为0.75
HashMap(int initialCapacity)
//将map表放到新的hashmap中
 public HashMap(Map<? extends K, ? extends V> m) 

源码分析三: Node对象 hashmap中存储的对象就是一个个node对象(1.7 取名是Entry),我们看看HashMap中静态内部类Node类的代码,其中hash就是哈希值,是通过哈希函数方法hash(Object key),在二进制中与运算获得的:

static class Node<K,V> implements Map.Entry<K,V> {
    final int hash;
    final K key;
    V value;
    // 指向下一个节点 ,模拟链表中指针的概念
    Node<K,V> next;
     // 构造函数。    
    // 输入参数包括"哈希值(h)", "键(k)", "值(v)", "下一节点(n)"    
    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; }

    public final int hashCode() {
        return Objects.hashCode(key) ^ Objects.hashCode(value);
    }

    public final V setValue(V newValue) {
        V oldValue = value;
        value = newValue;
        return oldValue;
    }
    // 判断两个Node是否相等 ,重写equals
    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 int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

源码分析四:方法
1.put方法:

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

hash(key)即哈希函数
key的hashcode()用&运算,获得哈希值,&运算,就是的数组的长度始终报纸2的次幂,是的二进制低位保持1,就能保证得到的新的数组索引和老数组索引一致
在这里插入图片描述
在这里插入图片描述
&运算,高位是不会对结果产生影响的,使得更加散列

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
               //声明数组,节点
    Node<K,V>[] tab; Node<K,V> p; int n, i;
//如果数组为null就resize() 方法初始化,大小返回为n
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
     //(n - 1) & hash,这个是这个散列表的哈希函数,计算出哈希值(数组下标i),判断tab[i]是否为null,为null则代表数组的这个位置为空, newNode创建对象节点Node(属性包括hash值,key,value 和 指针)加入数组,同时也作为散列表链表部分的头节点
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    else {
  //如果tab[i] 有值,这发生hash碰撞,对象就需要加入链表
        Node<K,V> e; K k;
     // 如果tab[i]的哈希值等于要加入元素的哈希值,且key相等,这对象相等,当tab[i]对象替换成加入的元素
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
           //判断是否为红黑树形式,p节点是红黑树,则走此逻辑
        else if (p instanceof TreeNode)
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
           //不是红黑树,这加入链表
        else {
       //循环链表
            for (int binCount = 0; ; ++binCount) {
          //p.next=null 链表指针指向null,表示这个链表最后一个节点
                if ((e = p.next) == null) {
                //将p.next指针指向新的对象node,成功加入链表
                    p.next = newNode(hash, key, value, null);
                 //链表长度大于等于8,则将链表转成红黑树,跳出循环,在  treeifyBin(tab, hash)方法中,可以看到这么一段
 if (tab == null || (n = tab.length) <MIN_TREEIFY_CAPACITY) resize(); 表示如果数组长度小于64,数组先扩容,先不转红黑树~~ 
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        treeifyBin(tab, hash);
                    break;
                }
                //这里和上面一样,循环链表中遇到hash值相同,则直接替换掉链表上的对象
                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;
//这里如果size 大于阈值了,resize()扩容    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}

2.get方法 get方法大致就是通过key获得hash值,通过hash值找到对应的node,返回value属性

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

扩容机制

在 HashMap 中,桶数组的长度均是2的幂,阈值大小为桶数组长度与负载因子的乘积。当 HashMap 中的键值对数量超过阈值时,进行扩容。

HashMap 按当前桶数组长度的2倍进行扩容,阈值也变为原来的2倍(如果计算过程中,阈值溢出归零,则按阈值公式重新计算)。扩容之后,要重新计算键值对的位置,并把它们移动到合适的位置上去。

final Node<K,V>[] resize() {
    // 拿到数组桶
    Node<K,V>[] oldTab = table;
    int oldCap = (oldTab == null) ? 0 : oldTab.length;
    int oldThr = threshold;
    int newCap, newThr = 0;
    // 如果数组桶的容量大与0
    if (oldCap > 0) {
        // 如果比最大值还大,则赋值为最大值
        if (oldCap >= MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return oldTab;
        }
        // 如果扩容后小于最大值 而且 旧数组桶大于初始容量16, 阈值左移1(扩大2倍)
        else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                 oldCap >= DEFAULT_INITIAL_CAPACITY)
            newThr = oldThr << 1; // double threshold
    }
    // 如果数组桶容量<=0 且 旧阈值 >0
    else if (oldThr > 0) // initial capacity was placed in threshold
        // 新容量=旧阈值
        newCap = oldThr;
    // 如果数组桶容量<=0 且 旧阈值 <=0
    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);
    }
    // 更新阈值
    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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值