浅谈JDK1.8之后的HashMap

浅谈JDK1.8之后的HashMap

跟同事聊天的时候,聊到HashMap,在java8下是有数组+链表+红黑树组成,在map的size达到一定长度之后,会由链表转换成红黑树。这引发了我的强烈好奇心,为什么1.8会进行链表跟红黑树之间的转换,在什么情况下会进行转换?

于是我就开始上网查资料,看源码,知道了HashMap里面的成员变量的意思

//数组默认初始容量:16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
//数组最大容量2 ^ 30 次方
static final int MAXIMUM_CAPACITY = 1 << 30;
//默认负载因子的大小:0.75
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// 树形最小容量:哈希表的最小树形化容量,超过此值允许表中桶转化成红黑树
static final int MIN_TREEIFY_CAPACITY = 64;
// 树形阈值:当链表长度达到8时,将链表转化为红黑树
static final int TREEIFY_THRESHOLD = 8; 
//树形阈值:当长度小于6时,将红黑树转化为链表
static final int UNTREEIFY_THRESHOLD = 6; 
//hashmap修改次数
transient int modCount; 
//可存储key-value 键值对的临界值 需要扩充时;值 = 容量 * 加载因子
int threshold;
//已存储key-value 键值对数量
transient int size; 
//负载因子
final float loadFactor; 
// 缓存的键值对集合
transient Set< Map.Entry< K,V >> entrySet; 
//链表数组(用于存储hashmap的数据)
transient Node< K,V>[] table;

由此可知在map的sizi大道8是,会由链表转换成红黑树,而当sizi小于或等于6时则会由树转换成链表。

回归原始问题,为什么1.8会进行链表跟红黑树之间的转换,在什么情况下会进行转换?

带着这个疑问:我在源码中找到了下面的一段。
This map usually acts as a binned (bucketed) hash table, but
when bins get too large, they are transformed into bins of
TreeNodes,翻译过来就是:这个映射通常充当一个已绑定(已加括号)的哈希表,但是当箱子变得太大时,它们就会被转换成 TreeNodes
在这里插入图片描述
而关于有红黑树转换成链表,我在HashMap的源码中找到有这样一描述:
Because TreeNodes are about twice the size of regular nodes, we use them only when bins contain enough nodes to warrant use.翻译过来就是:因为树节点的大小是普通节点的两倍,只有当容器包含足够的节点时才使用它们
在这里插入图片描述
至于为什么大于或等于8是用的红黑树,小于或等于6则使用的链表呢?
通过对他们两个的查询速度进行对比,我就知道了,因为红黑树的平均查找长度是log(n),所以当长度为8,查找长度为log(8)=3,而链表的平均查找长度为n/2,所以当长度为8时,平均查找长度为8/2=4,这才有转换成树的必要。至于为什么是6又转换回链表,则是在查询速率相差不大的情况下,有一个差值7可以则可以防止对HashMap进行频繁的插入跟删除操作时,防止链表和树之间的频繁的转换。

在解决了最初的问题之后,就想知道HashMap的是如何进行put操作跟get操作的,就开始了继续撸源码。先来put

/**
     * 将指定值与此映射中的指定键关联。如果映射之前包含键的映射,则替换旧值。
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with <tt>key</tt>, or
     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
     *         (A <tt>null</tt> return can also indicate that the map
     *         previously associated <tt>null</tt> with <tt>key</tt>.)
     */
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
    /**
     * Implements Map.put and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value
     * @param evict if false, the table is in creation mode.
     * @return previous value, or null if none
     */
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        //当tab为空或者长度==0时则进行扩容重构hashmap
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //通过hash跟key找到对应指定的位置,若未被使用则直接进行赋值操作
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {//若对应的地址已经被使用发生冲突了,则进行分别处理
            Node<K,V> e; K k;
            //若地址相同则替换
            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);
                        //当链表长度大于或等于7,就将链表转换成红黑树,然后将节点插入
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            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
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        // 如果容量不足 就继续扩容
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

再来get

/**
     * 返回指定键映射到的值,或{@code null},如果此映射不包含键的映射。更正式,如果这个映射包含一个
     * 键的映射{@code k}到一个值{@code v},使得{@code (key==null ?k = =零:key.equals(k))},
     * 则该方法返回{@code v};否则它返回{@code null}。(最多可以有一个这样的映射。)一个{@code null}
     * 的返回值不一定表示该映射不包含键的映射;这也是可能映射显式地将键映射到{@code null}。可以使用
     * {@link #containsKey containsKey}操作区分这两种情况。
     *
     * @see #put(Object, Object)
     */
    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;
        // 当表不为空,长度不为0且指定位置hash表内有值时
        if ((tab = table) != null && (n = tab.length) > 0 &&
        (first = tab[(n - 1) & hash]) != null) {
        	//若对应的key相同则直接返回
            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);
                //当对应的节点为链表时,匹配每个节点的key,返回匹配的对应值,直到下一个节点为空
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值