JDK1.8-HashMap源码学习

JDK1.8-HashMap源码学习

2020-10-30

HashMap概述

1、HashMap是哈希表的Map接口非同步实现。

  • HashMap提供所有可选的映射操作,并允许null值和null键。
  • HashMap不保证集合元素的顺序,特别是它不保证该顺序恒久不变。

2、HashMap设计用来快速访问键值对,它里面的元素是没有顺序的。

3、
HashMap的数据结构:
HashMap内部是一个“链表散列”的数据结构,即数组+链表+红黑树的结合体。

HashMap底层就是一个数组结构,数组当中的每一项又是一个链表/红黑树。
新建一个HashMap的时候,就会初始化一个数组。

一、数组节点的数据结构定义

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

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

1、类的属性值有4个:

  • hash:根据关键字key计算得到的数组下标值。
  • key:即存储关键字。
  • value:与关键字关联的值。
  • next:指向下一节点的指针。这个是链表的特征,当关键字生成的hash有重复时,就使用到链表存储元素。

二、往HashMap存入元素过程

先看源码的put方法:

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

putVal()方法源码,先理解几个参数的含义:

  • hash:存储关键字KEY的哈希值。
  • value:与KEY关联的值。
  • onlyIfAbsent:如果为true,请不要更改现有值;如果为false,则更新现有值。
  • 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)
            // 当数组为null时,初始化数组
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            // 根据KEY计算得到数组下标的位置没有元素,就把当前元素存放到数组下标的位置
            tab[i] = newNode(hash, key, value, null);
        else {      
            // 产生hash冲突,即有重复元素要存放到同一个数组下标的位置
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                // 关键字相同,更新value
                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
                            // 当链表元素个数超过8时,将链表转为红黑树,这样可以提高查询效率
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        // 遍历同一个KEY,跳出循环
                        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;
    }

HashMap存储过程小结

1、当我们往HashMap当中存放元素的时候,首先根据key的hashCode计算hash值,根据hash值得到这个元素在数组当中的下标。

2、如果数组该位置已经存放有其他元素了,那么在这个位置上的元素将以链表的形式存放,新加入的元素放在链表头,最先加入的元素放在链表尾。

3、如果该位置上没有元素,就直接将该元素放到此数组的该位置上。

三、从HashMap读取元素的过程

get()方法源码:

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

getNode()方法源码:

    final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        // 首先根据hash值计算对应下标位置,判断KEY是否相同
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            // always check first node
            if (first.hash == hash &&  ((k = first.key) == key || (key != null && key.equals(k))))
                // KEY相同,找到对应value,返回值。
                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读取过程小结:

1、首先计算key的哈希值,找到数组中对应位置的某一元素。

2、如果该位置存在元素/链表组/红黑树,则通过key的equals()方法在对应位置的链表/红黑树当中找到需要的元素值。

3、如果该位置不存在元素,则返回null。

HashMap的resize操作,扩容操作

1、HashMap要扩容的原因:

当HashMap中的元素越来越多的时候,hash冲突的几率也就越来越高,因为HashMap中数组的长度在初始化后是固定的,所以为了提高查询的效率,就要对HashMap的数组进行扩容。扩容这是在集合接口当中很常用的操作。

2、扩容的坏处:

在HashMap数组扩容后,最消耗性能的点就出现了:

原数组当中的数据必须重新计算在新数组当中的位置,并且存放进去,这就是扩容(resize)。

3、什么时候扩容?

当HashMap中的元素个数超过数组大小*loadFactor时,HashMap就会进行数组扩容操作,loadFactor的值默认为0.75,这是一个折中的取值。

默认情况下,HashMap内部的数组大小为16,那么当HashMap中元素个数超过160.75=12的时候,HashMap就会把数组的大小扩展为216=32,即数组容量增大一倍,然后重新计算每个元素在数组当中的位置,而这是一个非常消耗性能的操作。

所以如果我们已经预知HashMap当中元素的个数,那么在初始化HashMap时设置元素个数能够有效提升HashMap的性能。

4、数组扩容增大多少?

数组容量增大为原来的一倍。

5、为什么HashMap数组的长度是2的倍数?

找索引时 key 的 hash 值与数组的长度值减 1 进行与运算,长度为 2 的倍数时能减少碰撞。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值