HashMap原理

Posted 哈特谢普苏特

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HashMap原理相关的知识,希望对你有一定的参考价值。

1.构造器

hashmap有四个构造器

(1) HashMap() 如下所示代码  DEFAULT_LOAD_FACTOR = 0.75f

    /**
     * Constructs an empty <tt>HashMap</tt> with the default initial capacity
     * (16) and the default load factor (0.75).
     */
    public HashMap() 
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    

默认的初始大小为16 

    /**
     * The default initial capacity - MUST be a power of two.
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

 

(2)HashMap(int initialCapacity)

    public HashMap(int initialCapacity) 
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    

 在(2)的情况下,最终会调用(3),如果我们initialCapacity = 10,在(3)中经过tableSizeFor(),HashMap的threshold最终为16.

(3) HashMap(int initialCapacity, float loadFactor)

    public HashMap(int initialCapacity, float loadFactor) 
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        this.loadFactor = loadFactor;
        this.threshold = tableSizeFor(initialCapacity);
    

tableSizeFor() 函数将输入的cap通过位运算(或运算)变成一个大于等于cap且是2的幂的一个数并 返回。

    static final int tableSizeFor(int cap) 
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    

 (4)HashMap(Map<? extends K, ? extends V> m)

    /**
     * Constructs a new <tt>HashMap</tt> with the same mappings as the
     * specified <tt>Map</tt>.  The <tt>HashMap</tt> is created with
     * default load factor (0.75) and an initial capacity sufficient to
     * hold the mappings in the specified <tt>Map</tt>.
     *
     * @param   m the map whose mappings are to be placed in this map
     * @throws  NullPointerException if the specified map is null
     */
    public HashMap(Map<? extends K, ? extends V> m) 
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    

在这里会调用putMapEntries()方法

    /**
     * Implements Map.putAll and Map constructor.
     *
     * @param m the map
     * @param evict false when initially constructing this map, else
     * true (relayed to method afterNodeInsertion).
     */
    final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) 
        int s = m.size();
        if (s > 0) 
            if (table == null)  // pre-size
                //构造器调用 因此table == null 
                float ft = ((float)s / loadFactor) + 1.0F;
                //浮点数ft的值为传入的map的大小除以loadFactor + 1.0f,加1.0f是为了向上取整,这可能会导致一定的问题
                int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                         (int)ft : MAXIMUM_CAPACITY);
                if (t > threshold)
                    //如果t大于threshold 则进行tablseSizeFor()
                    //实际上如果是构造器调用的putMapEntries()threshold默认为0,因此肯定会调用tableSizeFor()方法
                    threshold = tableSizeFor(t);
            
            else if (s > threshold)
                resize();
            for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) 
                K key = e.getKey();
                V value = e.getValue();
                putVal(hash(key), key, value, false, evict);
            
        
    

 

    /**
     * The next size value at which to resize (capacity * load factor).
     *
     * @serial
     */
    // (The javadoc description is true upon serialization.
    // Additionally, if the table array has not been allocated, this
    // field holds the initial array capacity, or zero signifying
    // DEFAULT_INITIAL_CAPACITY.)
    int threshold;

这是一个用(4)构造的HashMap, 在这种构造器中就会导致一个问题,如果传入的hashmap中有12个key-value键值对,那么在putMapEntries()中就会导致计算出来的浮点数ft 为17.0,从而导致新的hashmap在进行tableSizeFor时大小变为32而不是旧的hashmap的16。如下图debug结果。

import java.util.*;

public class HashMapDemo 
    public static void main(String[] args) 
        HashMap<String,Integer> oldMap = new HashMap<String,Integer>();
        for(int i=0;i<12;i++)
            oldMap.put(""+i,i);
        
        HashMap<String,Integer> newMap = new HashMap<String,Integer>(oldMap);
        System.out.println();//此处打断点
    

 2.put(),get()方法

(1)put()方法

    public V put(K key, V value) 
        return putVal(hash(key), key, value, false, true);
    
    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)
        //如果当前tab为null,则进行resize()
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            //如果当前位置为null,直接插入一个结点 位置为n-1 & hash
            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))))
                //如果当前有值且key相等 则进行替换
                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) 
                    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相等 同上 需要替换
                    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)
            //如果当前个数大于threshold 进行resize()
            resize();
        afterNodeInsertion(evict);
        return null;
    

这里用到了resize() 扩容为原来的2倍并通过e.hash() & oldCap 判断是否需要挪位

    final Node<K,V>[] resize() 
        Node<K,V>[] oldTab = 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)
                newThr = oldThr << 1; // double threshold
        
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        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;
        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;
    

(2)get() 获取hashmap中特定key的值很简单,通过hash获取结点即可

    public V get(Object key) 
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    
    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);
            
        
        //如果没有 返回null
        return null;
    

hashmap中的hash()函数,实际上是key进行hashcode后高16位和低16位进行异或操作 

    static final int hash(Object key) 
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    

3.线程不安全

(1)在进行put()操作的时候,假设线程A,B同时进行put操作且需要存入的值的key的hashcode()是相同的,并且此时当前槽位没有元素,当A,B都进行if ((p = tab[i = (n - 1) & hash]) == null)操作后,A被阻塞,而B继续执行并顺利将值存入。此时A开始继续运行(如果是线程安全的话,A本应该进行不为null的逻辑),但由于是线程不安全的,因此A会将B写的值进行覆盖。导致B的值丢失

(2)resize()操作

同样两个线程A和B,进行put()操作且刚好在同一槽位插入成功,需要进行扩容,由于jdk1.8是头插法,因此两个线程都需要进行扩容操作,假设此时A被阻塞,B先开始扩容,当B扩容结束后A此时开始继续执行,按照原来的逻辑A又进行了头插,最终导致当get()方法计算出来的位置刚好是发生多线程resize()的位置,最终导致死循环。

(3)put()中的++modCount

++本来就不是原子操作,多个线程同时put()很容易导致++modCount最终数值的不准确。

以上是关于HashMap原理的主要内容,如果未能解决你的问题,请参考以下文章

HashMap底层实现原理

(转)HashMap底层实现原理

HashMap底层实现原理及面试问题

HashMap底层实现原理及面试问题

23.说一下 HashMap 的实现原理?

HashMap底层原理以及与ConCurrentHashMap区别