对于HashMap只是学习了下put,remove方法,hashMap是数组+链表+红黑树组成

所以下面贴出我自己给代码的注释,看不懂的见谅哈,毕竟我也是刚了解,如果有错误的地方请指出,非常感谢

  put方法(图片和代码一起吧,屏幕小的时候 看图片合适点,看图片的话建议下载下来看,比较清晰):

学习HashMap的笔记

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)//判断table是否为null或者table的长度是否为0
        n = (tab = resize()).length;//调整table的长度
    if ((p = tab[i = (n - 1) & hash]) == null)//根据hash去获取table中的位置,如果为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))))//如果原数组中的元素和当前元素(需要新增的)hash一样并且{key相等或者(key不等于null并且key的equals相等)}
            e = p;//把当前数组中的元素赋值给e
        else if (p instanceof TreeNode)//如果当前数组中冲突的节点为红黑树
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);//插入红黑树
        else {//这里表示在冲突的hash桶中去查找为null的位置然后插入(有可能会遇见到达链表定义长度,这时需要转换成红黑树了)
            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))))//这里的条件和上面的判断一样,结果是为了如果找到hash想的并且key相等的表示存在
                    break;
                p = e;
            }
        }
        if (e != null) { // existing mapping for key
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)//如果onlyIfAbsent为true表示不覆盖原有的值(默认为false)
                e.value = value;//覆盖值
            afterNodeAccess(e);
            return oldValue;
        }
    }
    ++modCount;
    if (++size > threshold)//如果当前map的大小大于阈值了,进行扩容
        resize();
    afterNodeInsertion(evict);
    return null;
}
View Code

相关文章: