HashMap源码分析——put方法

static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);  //将h无符号右移16为相当于将高区16位移动到了低区的16位,
//再与原hashcode做异或运算,

// 可以将高低位二进制特征混合起来 }

 hashCode方法返回的类型是int,默认是对象的内存地址 , 占内存 32 byte 。

注:为什么使用异或运算:

    异或运算能更好的保留各部分的特征,如果采用&运算计算出来的值会向0靠拢,采用|运算计算出来的值会向1靠拢

以上代码是put方法中进行调用,用来执行哈希操作的 ,具体细节如下图:

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

执行完hash操作后,会产生一个哈希值,然后调用 putVal方法完成具体的put操作。在分putVal方法之前,先来分析下resize()扩容方法

在分析一个方法的源码之前,或者要加深对一个方法的了解,最好是从整体上能知道这个方法完成了什么,这样再细看源码时才有助于思路清晰,那么这个resize方法究意做了什么呢?

最直接了当的方式当然是看注释:

Initializes or doubles table size.   // 初始化数组大小或对数据进行加倍的扩容

If null, allocates in accord with initial capacity target held in field threshold.  //如果数组是null,就按 类的成员变量threshold的值进行容量的初始分配。

Otherwise, because we are using power-of-two expansion,  // 否则以2的冥次方形式进行扩容

the elements from each bin must either stay at same index,  //扩容后数组中每个桶中的元素还需要保存在新数据的同样的桶中。

or move with a power of two offset in the new table.     //或者在新表中以二次方偏移量整体移动到新的索引下

 final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;    
        int oldCap = (oldTab == null) ? 0 : oldTab.length;  // 获取原数组(后面称桶)的容量
        int oldThr = threshold;         //threshold初始值为0 , threshold表示当HashMap的size大于threshold时会执行resize操作
        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        //如果容量的阈值大于默认的初始值16且小于最大值,则左移一位即乘2进行扩容
        }
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;                                      //如果阈值初始就大于0,则直接使用,一般是通过有参构造方法设置的
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;                        //这种情况表示是用无参构造产生hashmap对象的,阈值初始为0,则设置容量为默认的16,阈值为12
            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;                                         //创建产生新的桶
        if (oldTab != null) {                             //如果老数组不为空,那么涉及到元素的转移操作
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {   //先将桶中的元素赋值给e
                    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;
    }

 下面详细分析putVal方法:

 1  final V putVal(int hash, K key, V value, boolean onlyIfAbsent,     // 参数说明
 2                    boolean evict) {
 3         Node<K,V>[] tab; Node<K,V> p; int n, i;
 4         if ((tab = table) == null || (n = tab.length) == 0)          // table为HashMap定义的成员变量 , 如果table为null或者数组长度为0则进行扩容
 5             n = (tab = resize()).length;                             // resize()扩容方法,n保存扩容后的长度
 6         if ((p = tab[i = (n - 1) & hash]) == null)        // i = (n - 1) & hash 确定要保存存的节点的数组索引的位置  ,并且p设置为该索引处的指针
 7             tab[i] = newNode(hash, key, value, null);        //如果当前索引位置元素为null,则在此保存要put的元素
 8         else {                 //表示索引处之前已有元素
 9             Node<K,V> e; K k;
10             if (p.hash == hash &&                                              //如果要put的元素的hash值与已存在元素的hash值相同
11                 ((k = p.key) == key || (key != null && key.equals(k))))        //   (k = p.key) == key判断是不是同一个对象 或者 key不为null且key的值相等
12                 e = p;                                                         // 表示在数组上找到与put的key相匹配的元素,并将该元素赋给e
13             else if (p instanceof TreeNode)                                    // 如果如果桶上面是个TreeNode,那需要在树上进入插入
14                 e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
15             else {                                                             //否则在链表上进行插入
16                 for (int binCount = 0; ; ++binCount) {
17                     if ((e = p.next) == null) {
18                         p.next = newNode(hash, key, value, null);
19                         if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
20                             treeifyBin(tab, hash);
21                         break;
22                     }
23                     if (e.hash == hash &&
24                         ((k = e.key) == key || (key != null && key.equals(k))))
25                         break;
26                     p = e;
27                 }
28             }
29             if (e != null) { // existing mapping for key.  在树上或链表上找到了key相同的节点
30                 V oldValue = e.value;
31                 if (!onlyIfAbsent || oldValue == null)
32                     e.value = value;
33                 afterNodeAccess(e);
34                 return oldValue;
35             }
36         }
37         ++modCount;
38         if (++size > threshold)
39             resize();
40         afterNodeInsertion(evict);
41         return null;
42     }
原文地址:https://www.cnblogs.com/hzhuxin/p/14728515.html