首页 > 经典面试题HashMap分析
头像
菜鸟也要飞的高
编辑于 2020-11-19 10:15
+ 关注

经典面试题HashMap分析

HashMap中的静态变量意义

  1. static final int DEFAULT_INITIAL_CAPACITY = 1 << 4

为默认HashMap初始化的容量,即当你new HashMMap<>(),此时默认初始化容量为16

  1. static final float DEFAULT_LOAD_FACTOR = 0.75f;

加载因子, 默认为0.75 当加载因子过大时,会加剧哈希碰撞,过小会占内存

  1. static final int TREEIFY_THRESHOLD = 8;

JDK1.8中当拉链中的元素个数大于8时,会转换为红黑树

  1. static final int UNTREEIFY_THRESHOLD = 6;

当拉链中元素个数小于6个时,会把红黑树重新转换为拉链

  1. static final int MIN_TREEIFY_CAPACITY = 64;

容量小于 MIN_TREEIFY_CAPACITY,只会进行简单的扩容。容量大于 MIN_TREEIFY_CAPACITY ,则会进行树化改造。

关健源码的分析

  1. 构造函数
     public HashMap(int initialCapacity, float loadFactor) {
         if (initialCapacity < 0)
             throw new IllegalArgumentException("Illegal initial capacity: " +
                                                initialCapacity);
         if (initialCapacity > MAXIMUM_CAPACITY)
             initialCapacity = MAXIMUM_CAPACITY;
         if (loadFactor <= 0 || Float.isNaN(loadFactor))
             throw new IllegalArgumentException("Illegal load factor: " +
                                                loadFactor);
         this.loadFactor = loadFactor;
         this.threshold = tableSizeFor(initialCapacity);
     }
    

从构造函数可以看出HashMap最大size为MAXIMUM_CAPACITY,而MAXIMUM_CAPACITY则为1<<30

  1. get方法
    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) {
                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;
    }

1.tab[(n - 1) & hash]获取key对应的hash槽
2.判读首节点是否为空,为空的话return,不为空继续判断首节点是否和想要查找的节点值相等,相等直接返回
3.之后找next节点,先判断空,不为空的情况下首先进入树形节点,然后遍历判断,如果没有找到进行下一步
4.进入链表节点进行查找

  1. put方法

     final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                    boolean evict) {
         Node<K,V>[] tab; Node<K,V> p; int n, i;
    
          //如果数组为空或者length==0的话需要先进行初始化的工作
         if ((tab = table) == null || (n = tab.length) == 0)
             n = (tab = resize()).length;
         // 获取对应key的hash值,并且看对象的hash槽中有没有元素占用了,也就是说有没有发生hash碰撞,如果没有直接创建元素节点
         if ((p = tab[i = (n - 1) & hash]) == null)
             tab[i] = newNode(hash, key, value, null);
         else {
         // 如果发生了hash碰撞
             Node<K,V> e; K k;
         // 如果给定的key是map 中已经存在的,那么直接覆盖原来的元素
             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 {
             //如果不是树类型那么就是链表类型,循环判断直到节点为null或者跟指定的节点值相等
                 for (int binCount = 0; ; ++binCount) {
                    //节点为null则需要new 新节点
                     if ((e = p.next) == null) {
                         p.next = newNode(hash, key, value, null);
                         if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                             // 链表长度大于8 (因为要加上新节点的值,所以这里判断其实是>=7),并且整个map的大小大于了64转换为红黑树
                             treeifyBin(tab, hash);
                         break;
                     }
                     if (e.hash == hash &&
                         ((k = e.key) == key || (key != null && key.equals(k))))
                         break;
                     p = e;
                 }
             }
         // 上面的逻辑走完 的话 如果e不为null 也就是说 map中已经存在了该key,那么替换value ( onlyIfAbsent如果这个值为true则不会做替换,但是在map.put中传入参数时这个值为false所以后续会做替换)
             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 resize

    final Node<K,V>[] resize() {
        // oldTab存储为旧值
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        // 加载因子
        int oldThr = threshold;
        int newCap, newThr = 0;
        // 确定现在的map中是否有值
        if (oldCap > 0) {
            //如果容量超过最大值就不会扩容直接返回
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            // 扩容旧的容量*2并且判断会不会超过最大值,并且需要大于等于16
            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;
                    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;
    }

面试问题

  1. HashMap JDK1.8有什么优化?
  2. HashMap使用过程中可以做那些优化?
  3. 多线程HashMap中resize过程中是如果形成死锁的
  4. 加载因子大小,有什么作用?
  5. HashMap与HashTable的区别
  6. Hashap与CurrentHashMap的区别
  7. HashMap底层原理
  8. 为什么HashMap的容量是2的幂次方?

全部评论

(5) 回帖
加载中...
话题 回帖

推荐话题

相关热帖

近期热帖

近期精华帖

热门推荐