深入解析HashMap源码(二)

接上章   深入解析HashMap源码(一) ,我们来看HashMap中一些核心的成员方法

  • hash方法

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

hash方法是用来计算key的hashCode,并且优化了散列值,减少了hash碰撞(散列值用来定位数组里数据的下标)。为什么不使用初始散列值呢,因为散列值的大小是从(-2^31)~(2^31-1),这样的数组有着超过40亿的长度,很明显内存是放不下的,所以hash方法里用到了(h = key.hashCode()) ^ (h >>> 16)的操作,即将hashCode的高16位和低16位做异或运算(符号^),如图所示

这里进行完高位运算后,在后面对hash的操作中又做了一个运算:取模运算

static int indexFor(int h, int length) {  
     return h & (length-1);  
}

这个运算在jdk1.7里以indexFor方法的形式显示,jdk1.8取消了这个方法,但是操作的原理是一样的,如下图

所以在jdk1.8里,增加了异或运算,并将结果和length-1进行&运算。h右移16位,正好是32bit的一半,这样的高位低位混合,在增大低位的随机性同时,也保留了高位的部分数据信息,如下图所示

  • resize方法

resize()实现了对Node数组的初始化或改变容量大小。如果数组为null,则按照字段DEFAULT_INITIAL_CAPACITY中保持的初始容量目标进行分配,否则,由于我们使用的是两倍展开的幂,每个桶中的元素要么保持相同的索引,要么在新表中以两倍偏移量的幂(^(n+1))移动。

我对源码的步骤做了注释,让我们来看看源码是怎么实现这个方法的

 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) {
            //旧容量大于最大值2^30时,不再扩容
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            //新容量是旧容量的2倍,同时设置阈值,都是<<1
            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);
        }
        //newThr 为 0 时,按阈值计算公式进行计算
        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"})
        //创建新的bucket数组
        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)
                        //新的数组下标,通过&运算获得
                        [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;
    }

resize方法的主要逻辑是:

1. 计算新的容量newCap和新的阈值newThr

2. 根据newCap来初始化新的bucket数组

3. 将原先的键值对数组赋给新的数组

4. 返回扩容后的数组

  • get/getNode方法

get方法是用来查找数组中的数据的,通过传入key的方式获取对应的value

 public V get(Object key) {
        Node<K,V> e;
        //调用getNode方法
        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) {
                //若果first为红黑树节点,调用树节点查找方法
                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;
    }

getNode方法的主要逻辑是:

1. 定位键值对位置

2. 调用对应的查找方法(数组或链表)

3. 返回map键值对对象

  • put/putVal方法

put方法是用来往HashMap里插入数据的,具体实现逻辑简单化可以是

1. 定位插入数据属于哪个桶

2. 判断桶是否为空

3. 存入,更新,或在链表节点后增加

但是,还存在两个问题,一是插入数据过多时需要进行扩容操作,二是需要对红黑树和链表进行转化。让我们来看看代码实现逻辑

public V put(K key, V value) {
        //调用putVal方法
        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)
            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;
            //判断键的hash是否等于第一个键值对的hash
            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);
                        //超过树转化阈值时,转化为红黑树
                        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;
                }
            }
            // 判断要插入的键值对是否存在 HashMap 中
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                //当旧的value为null时,更新value
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        //容量撑不住了,该扩容了
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }
  • remove方法

HashMap 的删除操作和前面的操作并没有特别的地方。主要逻辑是:

1. 定位桶位置

2. 遍历链表并找到键值相等的节点

3. 删除节点。

public V remove(Object key) {
        Node<K,V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
            null : e.value;
    }

    final Node<K,V> removeNode(int hash, Object key, Object value,
                               boolean matchValue, boolean movable) {
        Node<K,V>[] tab; Node<K,V> p; int n, index;
        //判断和定位桶的位置
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (p = tab[index = (n - 1) & hash]) != null) {
            Node<K,V> node = null, e; K k; V v;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                node = p;
            //红黑树判断
            else if ((e = p.next) != null) {
                if (p instanceof TreeNode)
                    node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
                else {
                    //链表遍历
                    do {
                        if (e.hash == hash &&
                            ((k = e.key) == key ||
                             (key != null && key.equals(k)))) {
                            node = e;
                            break;
                        }
                        p = e;
                    } while ((e = e.next) != null);
                }
            }
            //删除节点
            if (node != null && (!matchValue || (v = node.value) == value ||
                                 (value != null && value.equals(v)))) {
                if (node instanceof TreeNode)
                    ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
                else if (node == p)
                    tab[index] = node.next;
                else
                    p.next = node.next;
                ++modCount;
                --size;
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }

 以上就是常用的也是比较重要的HashMap里的方法了,还有一些方法没有列举出来(太多了...),列举的方法如果注释有错误的地方也希望各位能不吝赐教^_^

猜你喜欢

转载自blog.csdn.net/qq_36182135/article/details/81434135