hashmap底层实现

版权声明:本文为博主原创文章,转载请注明出处 https://blog.csdn.net/qq_36819098/article/details/80345258

HashMap的底层实现

分析put方法

①.当调用put方法向hashmap增加元素时,会先判断hashmap里的数组是否null或数组长度为0,是就进行resize()操作,否就进行下一步判断;

②.根据put时传递的参数key计算出的hash值,让这个值和数组长度减一的结果进行按位与运算,得到put进去的key-value要放在数组的哪个位置上(以下称table[i]),如果该位置为null,直接添加元素,否则进入下一步;

③.接下来会判断添加的元素是否和table[i]上的元素的key是否相等(相等指的是hash值和equals方法),相等就会覆盖,不相等继续判断table[i]是否是红黑树节点;

④.如果table[i]是TreeNode(是红黑树),则直接在树中插入键值对,否则遍历链表来进行插入操作;

⑤遍历table[i]节点的链表,插入到链表尾部(jdk1.8用尾插法,jdk1.8以前的版本用头插法),遍历过程中发现key已经存在,则会替换。如果插入后链表长度大于8,会把链表转换成红黑树结构;

⑥.插入成功后,modCount自加,size自加,判断hashmap的元素个数是否超过阈值,超过阈值就进行resize()。

public V put(K key, V value) {
//key进行计算hash
    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;

//计算出要存放在数组中的位置tab[i]tab[i]null就直接插入
   
if ((p = tab[i = (n - 1) & hash]) == null)
       
tab[i] = newNode(hash, key, value, null);
   
else {
       
Node<K,V> e; K k;

//tab[i]节点存在且和要插入的key-value相等,此时覆盖tab[i]
       
if (p.hash == hash &&
           
((k = p.key) == key || (key != null && key.equals(k))))
           
e = p;

//判断tab[i]是否是红黑树结构
       
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;
               
}

//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)
       
resize();
    afterNodeInsertion(evict);
    return null;
}

 

 扩容机制

当hashmap里添加了一定数量的元素时(数量达到阈值),就需要扩大数组。使用一个新的更大的数组代替已有的容量小的数组。


  /**
 * Initializes or doubles table size.  If null, allocates in
 * accord with initial capacity target held in field threshold.
 * Otherwise, because we are using power-of-two expansion, the
 * elements from each bin must either stay at same index, or move
 * with a power of two offset in the new table.
 *
 * @return the table
 */
  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) {
//扩容前数组大小已经达到最大(2^30),把阈值调到最大,以后就不能再扩容了
        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; //将原数组中存放的引用置为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;
}

在jdk1.8中Hashmap的扩容是2次幂的扩容(指长度扩为原来的2倍),所以元素的位置要么在原位置要么在移动2次幂的位置。

在数组长度为16的hashmap中,有key1的hash值为4,有key2的hash值为20

元素在新的数组中的位置计算公式:e.hash & (newCap - 1)

数组长度为16,参与运算的是16-1,15对应的二进制为   00001111

扩容后数组长度为32,参与运算的是31,对应的二进制为 00011111

Hash值         4               20  

二进制        00000100        00010100

 

原容量15     00001111        00001111     这是key的hash值的二进制与oldCap-1进行计算

结果         00000100        00000100     计算得出的原位置(此时位置相同) 

 

新容量31     00011111        00011111     这是key的hash值的二进制与newCap-1进行计算

结果         00000100         00010100     得出在新数组中要存放的位置(此时位置不同)

 

 

参考:

1.美团技术点评,Java 8系列之重新认识HashMap,2016。

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页