HashMap的学习

学习目的(基于JDK8):

什么是HashMap以及它的特性

Hashcode,equals,==的区别

HashMap的数据结构

hashMap的工作原理

HashMap的扩容

HashMap是否线程安全?如果不是怎么使HashMap变得线程安全

1.什么是HashMap以及它的特性

HashMap首先是一个map,所以它和map一样用于存储键值对(key-value)的集合类,也可以说是一组键值的映射关系。HashMap是用哈希表(数组+单链表)+红黑树实现的map。
在这里插入图片描述
当链表的长度大于8时,会转变为红黑树结构进行存储。

特性:

允许空值和空键,空键只能有一个

元素是无序的

key用Set存储,所以key不能重复,这也是为什么空键只能用有一个

实现了所有map的接口

2.HashCode、equals、==的区别

HashCode:由名称可以看出,这就是一个hash码,用于存储对象时,对对象进行散列作为key值存入。

equals:默认的,没有被覆盖的equal和==等效,重写的equal就要根据具体的重写来定义,例如String类重写的equals

public boolean equals(Object anObject) {  
    if (this == anObject) {  
        return true;  
    }  
    if (anObject instanceof String) {  
        String anotherString = (String)anObject;  
        int n = count;  
        if (n == anotherString.count) {  
        char v1[] = value;  
        char v2[] = anotherString.value;  
        int i = offset;  
        int j = anotherString.offset;  
        while (n-- != 0) {  
            if (v1[i++] != v2[j++])  
            return false;  
        }  
        return true;  
        }  
    }  
    return false;  
 }  

String类的equals在除了满足内存地址相同外,也可以在不满足内存地址相同,只需字符串的每一个字符一样也会返回true。

“= =”:比较的是2个对象的内存地址。对象是放在堆中的,引用地址放在栈中,所以==是对栈中的值进行比较,如果想要比较堆中的值,只能重写equals方法了。

3.HashMap的数据结构

HashMap的数据结构在jdk1.8之前是数组+链表的形式,在JDK1.8中,在此基础上有加入了红黑树的结构。虽然结构变的复杂了,但效率变得更高了。当要存储一个键值对时,会根据键(key)来进行hash散列,通过key的hash值来确定在数组中的位置,如果该位置已经有数据存储,发生了碰撞,就以链表的形式存储在数组的后面。当链表的长度达到一定长度时就会将链表形式的存储转变为红黑树形式的存储。那么为什么要将链表转化为红黑树来实现呢?

我们要知道,存在即合理。我们想一下,使用链表进行存储,其查询效率是O(n),这个效率在n很小的时候效率很高,但是随着存储的数据越来越多,链表的长度越来越长,其效率会逐渐下降。而链表的查询效率是O(log(n)),随着存入的数据越来越多,其效率逐渐超过链表的效率。

为什么在链表长度达到8以后就将链表转换为红黑树,在长度降为6以后又转换回链表?(阿里面试题)

我们知道,链表转换为红黑树就是拿空间换时间。这个问题在源码里可以看到。先找到转换的阀值定义如下:

/**
     * The bin count threshold for using a tree rather than list for a
     * bin.  Bins are converted to trees when adding an element to a
     * bin with at least this many nodes. The value must be greater
     * than 2 and should be at least 8 to mesh with assumptions in
     * tree removal about conversion back to plain bins upon
     * shrinkage.
     */
    static final int TREEIFY_THRESHOLD = 8;
​
    /**
     * The bin count threshold for untreeifying a (split) bin during a
     * resize operation. Should be less than TREEIFY_THRESHOLD, and at
     * most 6 to mesh with shrinkage detection under removal.
     */
    static final int UNTREEIFY_THRESHOLD = 6;

这里只说明了8是链表转为红黑树的阀值,并没有说明为什么。接着去源码的其他地方寻找答案。然后我们可以在Implementation notes中可以看到下面的注释,解释了为什么是8。

     * Because TreeNodes are about twice the size of regular nodes, we
     * use them only when bins contain enough nodes to warrant use
     * (see TREEIFY_THRESHOLD). And when they become too small (due to
     * removal or resizing) they are converted back to plain bins.  In
     * usages with well-distributed user hashCodes, tree bins are
     * rarely used.  Ideally, under random hashCodes, the frequency of
     * nodes in bins follows a Poisson distribution
     * (http://en.wikipedia.org/wiki/Poisson_distribution) with a
     * parameter of about 0.5 on average for the default resizing
     * threshold of 0.75, although with a large variance because of
     * resizing granularity. Ignoring variance, the expected
     * occurrences of list size k are (exp(-0.5) * pow(0.5, k) /
     * factorial(k)). The first values are:
     *
     * 0:    0.60653066
     * 1:    0.30326533
     * 2:    0.07581633
     * 3:    0.01263606
     * 4:    0.00157952
     * 5:    0.00015795
     * 6:    0.00001316
     * 7:    0.00000094
     * 8:    0.00000006
     * more: less than 1 in ten million

红黑树占用的空间是链表的2倍,所以只有当bin包含足够多的节点时才会进行转换(利益才是永恒的)。而判断节点是否足够多,就需要看是否大于TREEIFY_THRESHOLD。这段内容中提到,当hashcode的离散性很好的时候,tree几乎不会被用到。当离散性很好的时候,满足内容中所说的那个公式(泊松分布),根据概率,在大于8之后用到的概率是很小的,所以将阀值定为8。

4.HashMap的工作原理

HashMap是基于hashing的原理,通过put(key,value)对数据进行存储,首先会根据key的hashcode值获取在bucket中的位置,如果2个hashcode的值相同,即发生了哈希碰撞,就将对象以链表的形式链接在该位置下,当链表的长度超过阀值8,就会将链表转换为红黑树,以红黑树的形式进行存储。

 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;
    if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
    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))))
            //如果hashcode相等,且2个key==且equals,说明是同一个key直接覆盖
            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
                       //如果大于链表的阀值,将链表转换为红黑树
                       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)
        //如果大于存储阈值对hashmap进行扩容
        resize();
    afterNodeInsertion(evict);
    return null;
}
get()方法:

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

根据key进计算hash值获取在表中的位置

判断首节点是否是空,为空直接返回空

判断首节点的key是否和目标key相同,相同则返回节点

不相同,在判断首节点.next节点是否为空,为空返回空值

next节点是红黑树,进入红黑树节点取值

next节点是链表,进入链表取值

5.HashMap的扩容

resize()方法:

在put()方法中我们看到有一个resize方法,这个方法就是HashMap的扩容方法。先上源代码,再来分析:

final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        //如果table是空,直接初始化一个hashmap,返回一个空的table
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;//临界值
        int newCap, newThr = 0;
        if (oldCap > 0) {
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                //数组扩大2倍
                //临界值也扩大2倍
                newThr = oldThr << 1; // double threshold
        }
        else if (oldThr > 0) // initial capacity was placed in threshold
            //如果原来的thredshold大于0则将容量设为原来的thredshold
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults
            //默认无参时进行初始化
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        if (newThr == 0) {
            //如果新容量=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;
        //如果原来的table有数据,将数据移动到新的数组
        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)
                        //当前数组节点只有1个节点,e.hash & (newCap - 1)确定在新表中的位置
                        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;
    }

6.HashMap的线程安全性

HashMap是否线程安全?如果不是怎么使HashMap变得线程安全?

因为HashMap在发现容量大于0.75f的时候会自动扩容,当2个线程都发现HashMap需要扩容,容量变成2倍之后,会对里面的对象进行reHash,来确定在扩容之后的表里面的位置,当线程1在e指向key:0时,next指向key:1

在这里插入图片描述

此时线程2对整个HashMap扩容并重新计算位置并移动。
在这里插入图片描述

而在线程1中e和next的指向未有改变,e指向key:0,next指向key:1

1.执行e.next = newTable[i],因为线程1的新Hash表是空表,所以e.next = null

2.指向newTable[i]=e,所以新的Hash表的第一个元素指向了线程2的新Hash表的key:0

3.执行e=next,将e指向next节点,现在e是next指向的节点也就是key:1

在这里插入图片描述

可是线程2已经重新计算并移动了对象的位置,

key: 1的next指向的是key:0,所以将key:1插入table[0]的头节点

在这里插入图片描述

Entry<K,V> next = e.next,

执行e.next = newTable[i],所以key:0的next又指向了key:1

执行newTable[i]=e,那么table[0]的第一个元素又变成了key:1

执行e=next,e又变成了key:0

在这里插入图片描述

然后就会造成闭环,导致死循环,所以HashMap不是线程安全的。

如果觉得还可以,欢迎关注我的公众号:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值