HashMap1.8常见面试问题

1.hashmap转红黑树的时机:

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;
    }
上面代码在putval方法中:判断了当不存在的key插入map时,如果往node节点一直遍历当大于等于8次时,会转化尝试转化为红黑树,注意是尝试。

在treeifyBin方法中还会判断:
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
    resize()
;
当tab的长度也就是cap容量小于64时会resize而不是直接转化为红黑树.
综上:hashmap转红黑树的时机为当链表长度大于等于8并且容量大于等于64时。
 
2.hashmap put过程
源码如下:
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
  //tab为node数组,p为hash运算后的下标i的node节点,n为tab长度,i为node数组下标
    Node<K,V>[] tab; Node<K,V> p; int n, i;
  //hashmap采用懒加载思想,只有真正用的时候才会初始化
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
  //里面有个知识点 运算符的优先级 ()>&>= 所以先用长度-1和hash值与运算再赋给坐标i
    if ((p = tab[i = (n - 1) & hash]) == null)
    //tab[i]空直接插入
        tab[i] = newNode(hash, key, value, null);
    else {
  //e为后面要操作的node节点 k为node的key p为已存在的下标i的node节点
        Node<K,V> e; K k;
  //常问的重写hashcode和equals方法答案就在下面这句话
  //当p和e的hash值相同并且引用p,k相同或者key调用equals方法相同时直接覆盖
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
  //将把p赋给e,后续e都是我们默认操作的put的key的节点
            e = p;
        else if (p instanceof TreeNode)
  //如果是树则使用其他的put方法
            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;
            }
        }
 //上面链表遍历有3种结果 1.node链表长度小于8没有找到对应key,直接尾插法new一个node
              2.node链表大于8,尝试红黑树转换
              3.node链表长度小于8找到对应的key,跳出循环,此时e是有值
              所以我们说e是最后我们操作存在key的node节点
     //返回旧值,放入新值
        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;
}

 

3.hashmap resize过程

resize总结:1.获取新的容量和临界值

      2.创建新表将hashmap tab rehash 元素以原来下标或者二次幂的偏移量下标移动

 /**
     * 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
     */
   //二次幂展开,扩容后元素要么是原有下标,要么以二次幂偏移量
   //exp:假设容量为16 key的hash为16 1111&10000=0存放在tab[0]中 如果扩容后容量为32 那么rehash时11111&10000 就是tab[16] 所以以二次幂的偏移量移动 final Node<K,V>[] resize() { Node<K,V>[] oldTab = table;
     //oldTab==null 为了兼容初始化
int oldCap = (oldTab == null) ? 0 : oldTab.length; int oldThr = threshold; int newCap, newThr = 0; if (oldCap > 0) {
       //当容量大于允许最大容量时临界点为Integer最大值
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 //当oldThr是0时初始化
       newCap = DEFAULT_INITIAL_CAPACITY; newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); }
     //临界值还是为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"})
     //创建新tab Node
<K,V>[] newTab = (Node<K,V>[])new Node[newCap]; table = newTab; if (oldTab != null) {
        //遍历oldTab数组
for (int j = 0; j < oldCap; ++j) { Node<K,V> e; if ((e = oldTab[j]) != null) { oldTab[j] = null; if (e.next == null)
              //该下标只有一个node时直接放入新tab中 newTab[e.hash
& (newCap - 1)] = e; else if (e instanceof TreeNode) ((TreeNode<K,V>)e).split(this, newTab, j, oldCap); else { // preserve order
               //下面的代码分为了两个链表 其实就是把hash大于等于cap的和小于的分开 小于的在原位 大于等于的按照oldcap偏移量下标存放
               //并且采用了尾插法
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; }

 

posted @ 2022-06-27 16:00  sasuke。  阅读(57)  评论(0编辑  收藏  举报