JDK8 HashMap源码解析

HashMap常量

    /**
     * 初始化容量16,自定义容量也必须是2的幂次方
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    /**
     * 最大容量,如果容量超过该值,则使用该值
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;

    /**
     * 默认负载系数,当size > 初始容量 * 负载系数 时,触发扩容
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    /**
     * 树形结构阈值,并且该值必须大于2切至少为8,一边树形解构与其他结构之间的转换
     */
    static final int TREEIFY_THRESHOLD = 8;

    /**
     * 拆分树形结构为其他数据结构的阈值
     */
    static final int UNTREEIFY_THRESHOLD = 6;

    /**
     * 当哈希表所有元素个数至少超过64时,才允许转换为树形结构
     */
    static final int MIN_TREEIFY_CAPACITY = 64;

变量

  /**
     * 哈希数组,长度总是为2的幂次方
     */
    transient Node<K,V>[] table;

    /**
     * 缓存的entrySet
     */
    transient Set<Map.Entry<K,V>> entrySet;

    /**
     * HashMap的所有数据的数量
     */
    transient int size;

    /**
     * 哈希表的修改次数
     */
    transient int modCount;

    /**
     * 触发扩容的值(容量 * 负载系数)
     *
     * @serial
     */
    int threshold;

    /**
     * 负载系数,默认值0.75
     *
     * @serial
     */
    final float loadFactor;

构造函数

 /**
     * 使用指定容量大小和负载系数初始化一个空的HashMap
     *
     * @param  initialCapacity 初始容量大小(必须是2的幂次方,如果不是会自动转换为2的幂次方)
     * @param  loadFactor      负载系数(0-1.0之间的数据)
     * @throws IllegalArgumentException 容量大小为负数或者负载系数为异常数据时抛出异常
     */
    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
     *
     * @param  initialCapacity 初始容量
     * @throws IllegalArgumentException 当初始容量为负数是抛出异常
     */
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    /**
     * 使用默认容量大小(16)和默认负载系数(0.75)初始化一个控的HashMap
     */
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

    /**
     * 使用指定的Map和默认的负载系数初始化一个足够容纳Map中的映射数据的HashMap,改HashMap与        
     * Map具有一样的映射
     *
     * @param   m 需要映射的map
     * @throws  NullPointerException 如果初始化的map为null,则抛出异常
     */
    public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }

tableSizeFor分析

    /**
     * 通过位运算将该数组转成与之最接近的2的n次方数值
     * 比如:cap的值为3,则返回的值为2^2;
     * cap的值为8,则返回的值为8
     * cap的值为9,则返回的值为16
     * 传入的值cap,如果cap<=2^n,则返回2^n;如果2^n < cap <= 2^n+1,则返回2^n+1
     */
    static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }

hash算法


    static final int hash(Object key) {
        int h;
        // 如果key为null的话,那么则返回hash值为0
        // 让高16位也参与到hash值的运算中
        // 当数组的长度很短时,只有低位数的hashcode值能参与运算。
        // 让高16位参与运算可以更好的均匀散列,减少碰撞,进一步降低hash冲突的几率。
        // 并且使得高16位和低16位的信息都被保留了。
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
  • 如果key == null直接返回0,这也是为啥HashMap只能存储一个null键的原因
  • 计算key的哈希值,得到h
  • 将h的低16位与高16位进行异或操作

put过程分析

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

    /**
     *
     * @param key的hash值
     * @param key
     * @param value
     * @param 如果该参数为true,则在key值一样并且产生hash冲突时,不进行覆盖,保留之前的值
     * @param 如果为false,表示处于创建模式
     * @return 返回前一个值,如果没有返回null
     */
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        // tab:哈希表数组,在首次调用put方法时才进行初始化
        // p:当前散列表的元素
        // n:哈希表数组的长度
        // i: 路径寻址结果
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        // 如果tab为空,则进行初始化
        if ((tab = table) == null || (n = tab.length) == 0)
            // 初始化获得初始化哈希数组的默认长度
            n = (tab = resize()).length;
            // 找到具体的数组下标
            // 如果当前数组下标位置为null,则代表是没有产生冲突,是新元素,直接存放在该位置
            // 需要特别注意的是(n - 1) & hash,这块下面详细分析
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            // 如果key的hash值与key都一样,则根据onlyIfAbsent参数决定是否需要覆盖掉之前的值
            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) {
                // 如果next节点为null,则再next解决插入数据,也就是在链表后面插入数据
                    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(== 或 equals)
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                // 此时 break,那么 e 为链表中[与要插入的新值的 key "相等"]的 node
                        break;
                    p = e;
                }
            }
            // e!=null 说明存在旧值的key与要插入的key"相等"
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
            // 如果onlyIfAbsent 为false或者oldValue 为null,则进行值覆盖
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        // modCount: 表示散列表结构被修改的次数,替换Node元素的value不算
        ++modCount;
        // 如果 HashMap 由于新插入这个值导致 size 已经超过了阈值,需要进行扩容
        if (++size > threshold)
        // 达到扩容临界点,进行扩容
            resize();
        afterNodeInsertion(evict);
        return null;
    }

   /**
     * 把链表结构转换为红黑树结构
     */
    final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
        // 这里表明转换为红黑树不仅要节点元素长度大于8,而且还要节点元素大于64
        // 注意:这里的大小判断,是整个容器的大小,而不是HashMap的size
        // 如果不满足转换为红黑树条件,则进行扩容
        if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
            resize();
        else if ((e = tab[index = (n - 1) & hash]) != null) {
            TreeNode<K,V> hd = null, tl = null;
            do {
                TreeNode<K,V> p = replacementTreeNode(e, null);
                if (tl == null)
                    hd = p;
                else {
                    p.prev = tl;
                    tl.next = p;
                }
                tl = p;
            } while ((e = e.next) != null);
            if ((tab[index] = hd) != null)
                hd.treeify(tab);
        }
    }

       /**
         * 红黑树插入方法
         */
        final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
                                       int h, K k, V v) {
            Class<?> kc = null;
            boolean searched = false;
            TreeNode<K,V> root = (parent != null) ? root() : this;
            for (TreeNode<K,V> p = root;;) {
                int dir, ph; K pk;
                if ((ph = p.hash) > h)
                    dir = -1;
                else if (ph < h)
                    dir = 1;
                else if ((pk = p.key) == k || (k != null && k.equals(pk)))
                    return p;
                else if ((kc == null &&
                          (kc = comparableClassFor(k)) == null) ||
                         (dir = compareComparables(kc, k, pk)) == 0) {
                    if (!searched) {
                        TreeNode<K,V> q, ch;
                        searched = true;
                        if (((ch = p.left) != null &&
                             (q = ch.find(h, k, kc)) != null) ||
                            ((ch = p.right) != null &&
                             (q = ch.find(h, k, kc)) != null))
                            return q;
                    }
                    dir = tieBreakOrder(k, pk);
                }

                TreeNode<K,V> xp = p;
                if ((p = (dir <= 0) ? p.left : p.right) == null) {
                    Node<K,V> xpn = xp.next;
                    TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn);
                    if (dir <= 0)
                        xp.left = x;
                    else
                        xp.right = x;
                    xp.next = x;
                    x.parent = x.prev = xp;
                    if (xpn != null)
                        ((TreeNode<K,V>)xpn).prev = x;
                    moveRootToFront(tab, balanceInsertion(root, x));
                    return null;
                }
            }
        }

(n - 1) & hash分析

n:代表的是HashMap的容量大小

hash:key的hash值

举个例子:

        System.out.print((15 & hash("1"))+" ");
        System.out.print((15 & hash("2"))+" ");
        System.out.print((15 & hash("3"))+" ");
        System.out.print((15 & hash("4"))+" ");
        System.out.print((15 & hash("5"))+" ");
        System.out.print((15 & hash("6"))+" ");
        System.out.print((15 & hash("7"))+" ");
        System.out.print((15 & hash("8"))+" ");
        System.out.print((15 & hash("9"))+" ");
        System.out.print((15 & hash("10"))+" ");
        System.out.print((15 & hash("11"))+" ");
        System.out.print((15 & hash("12"))+" ");
        System.out.print((15 & hash("13"))+" ");
        System.out.print((15 & hash("14"))+" ");
        System.out.print((15 & hash("(15"))+" ");
        System.out.print((15 & hash("16"))+" ");
        System.out.print((15 & hash("17"))+" ");
        System.out.print((15 & hash("18"))+" ");
        System.out.print((15 & hash("19"))+" ");
        System.out.print((15 & hash("20"))+" ");
        System.out.print((15 & hash("21"))+" ");
        System.out.print((15 & hash("22"))+" ");

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

这个代码获取到的值为:
1 2 3 4 5 6 7 8 9 15 0 1 2 3 12 5 6 7 8 14 15 0 14 1 

从上面的示例可以得出:

使用(n - 1) & hash得到当前key在数组中的存储位置,也就是数组下标。因为(n - 1) & hash得到的数组下标是无序的,所以,HashMap的存储是无序的。

链表结构转换为红黑树示例

        // 初始化默认容量大小为16,负载因子为0.75的HashMap
        Map<String, String> map = new HashMap<>();
        int key = 1;
        map.put("1", "1");
        for (int i = 1; i < 66; i++) {
            key += 11;
            map.put(String.valueOf(key), String.valueOf(key));
        }

扩容

    /**
     * 初始化或者加倍扩容散列表大小
     *
     * @return 散列表
     */
    final Node<K,V>[] resize() {
        // 首次put会进行初始化,所以首次table会为null
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        // 否首次,进行扩容
        if (oldCap > 0) {
            // 容量大小超过最大容量,则使用最大容量值,已经无法扩容
            // 把触发扩容参数,赋值为Integer.MAX_VALUE
            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
            // 初始化默认容量为16,默认负载系数为0.75的HashMap
            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;
        // 本次hashMap扩容前,内部存在数据
        if (oldTab != null) {
            // 遍历数组
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    // 赋值给e之后,置空,释放内存,方便垃圾回收机制进行回收
                    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;
    }

        final void split(HashMap<K,V> map, Node<K,V>[] tab, int index, int bit) {
            TreeNode<K,V> b = this;
            // Relink into lo and hi lists, preserving order
            TreeNode<K,V> loHead = null, loTail = null;
            TreeNode<K,V> hiHead = null, hiTail = null;
            int lc = 0, hc = 0;
            for (TreeNode<K,V> e = b, next; e != null; e = next) {
                next = (TreeNode<K,V>)e.next;
                e.next = null;
                if ((e.hash & bit) == 0) {
                    if ((e.prev = loTail) == null)
                        loHead = e;
                    else
                        loTail.next = e;
                    loTail = e;
                    ++lc;
                }
                else {
                    if ((e.prev = hiTail) == null)
                        hiHead = e;
                    else
                        hiTail.next = e;
                    hiTail = e;
                    ++hc;
                }
            }

            if (loHead != null) {
                // 树节点小于等于6,拆分树形结构,把红黑树转换为链表结构
                if (lc <= UNTREEIFY_THRESHOLD)
                    tab[index] = loHead.untreeify(map);
                else {
                    // 已经是红黑树了
                    tab[index] = loHead;
                    if (hiHead != null) // (else is already treeified)
                        loHead.treeify(tab);
                }
            }
            if (hiHead != null) {
                if (hc <= UNTREEIFY_THRESHOLD)
                    tab[index + bit] = hiHead.untreeify(map);
                else {
                    tab[index + bit] = hiHead;
                    if (loHead != null)
                        hiHead.treeify(tab);
                }
            }
        }

扩容后链表位置变换原理 

默认数组长度为16,假设在16的基础上进行扩容,扩容后容量变成32;

设下标为15的容器中有n个元素,那么这些元素的hash值后4位一定都是1111;

因为索引是根据(length-1)& hash 计算得出的,15的二进制为1111,与运算是有0为0,那么hash值和((length-1)=1111)进行与运算得出1111,所以hash的后四位也只能是1111;

通过索引计算公式:(length-1)& hash可以得知,当长度为16是,hash的取值最多也只能去后四位;

所以当容量有16变成32之后,length-1的也由15变成31,二进制对应1111变成了11111,所以在hash的取值也由四位变成了五位。举个例子:

hash值的后五位为11111,length-1长度为31,二进制对应是11111,进行与运算之后,得到11111

hash值的后五位为01111,length-1长度为31,二进制对应是11111,进行与运算之后,得到01111

而在源码中,是和旧的数组长度进行与运算,如下:

(e.hash & oldCap),hash值与旧的数组长度进行与运算,而旧的数组长度为16,对应二进制为10000,所以参与计算的hash值有后面5位,又因为16的二进制后四位全部为0,还要与hash进行与操作,同时0与任何数进行与操作,结果都为0,所以(e.hash & oldCap)的结果只能是00000或者10000,从上面的例子及源码可以得出:

  • 扩容后的链表索引如果hash取后n位的第1位是0则在原位,是1则等于原索引+旧索引长度

扩容原理及链表转换为红黑树总结 

  • 当数字索引位置数据不为null时,直接在该数组位置上存放数据
  • 当key值与hash值都一致时,根据参数onlyIfAbsent决定是否替换或者是保留
  • 当key值与hash值不一致时,并且在索引在数组中存在数据时,则在该索引位置上,以链表的形式存放该数据
  • 当该索引上存在数据,并且链表长度大于等于8时,触发链表转换为红黑树方法;同时再转换红黑树方法里面进行第二次判断,如果当前容器总容量小于64时,则不转换为红黑树,只是触发扩容,不触发链表转换为红黑树,只有在链表大小>=8并且容器大小>=64时,才会进行链表转换为红黑树操作
  • 扩容条件:达到扩容阈值或者在未达到扩容阈值时,链表长度大于等于8

putIfAbsent与put的区别

    @Override
    public V putIfAbsent(K key, V value) {
        return putVal(hash(key), key, value, true, true);
    }

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

从源码中可以看出,putIfAbsent与put方法只有一个参数差别,那就是onlyIfAbsent。前面也讲过这个参数的作用,就是在key与hash都一致的情况下,决定是否进行值覆盖。比如

        map.putIfAbsent("1", "1");
        map.putIfAbsent("1", "2");
        System.out.println(map.get("1"));
        map.put("2", "3");
        map.put("2", "4");
        System.out.println(map.get("2"));

该代码执行的结果为:1 4

从上面示例可以得出

  • 使用putIfAbsent方法,如果后面put进入一样的key,则后面put的value会被忽略
  • 使用put方法,如果后面put进入一样的key,则后面put的value会被覆盖

compute方法使用

示例:

            default V compute(K key,
            BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
        Objects.requireNonNull(remappingFunction);
        // 获取对应key的值
        V oldValue = get(key);

        // 获取回调方法返回的值
        V newValue = remappingFunction.apply(key, oldValue);
        
        if (newValue == null) {
            // delete mapping
            // 如果返回值为null,并且该key之前存在值,则移除该key 
            if (oldValue != null || containsKey(key)) {
                // something to remove
                remove(key);
                return null;
            } else {
                // nothing to do. Leave things as they were.
                // 如果该key不存在值,则不做处理
                return null;
            }
        } else {
            // add or replace old mapping
            // 把该key值再map中添加或者替换掉
            put(key, newValue);
            return newValue;
        }
    }

        // 示例
        Map<String, String> map = new HashMap<>();
        map.put("2", "3");
        map.put("4", "4");
        map.compute("2", (key, value) -> {
            if (value == null || value.isEmpty()) {
                return "5";
            }
            if (value.equals("3")) {
                return "6";
            }
            return "8";
        });
        System.out.println(map.get("2"));
        map.compute("3", (key, value) -> {
            if (value == null || value.isEmpty()) {
                return "5";
            }
            if (value.equals("3")) {
                return "6";
            }
            return "8";
        });
        System.out.println(map.get("3"));
        map.compute("4", (key, value) -> "10");
        System.out.println(map.get("4"));
        System.out.println(map.toString());


输出结果:
6
5
10
{2=6, 3=5, 4=10}

从源码与示例中可以看出

  • 返回数据不为null,使用compute方法进行put数据,可以先进行比对,也可以直接赋值,最终数据都会更新在HashMap中。
  • 返回value为null,并且存在该key的值或者包含该key,则会进行移除。
  • 返回value为null,如果不存在该key或者该key的value为null,则不处理

computeIfAbsent方法使用

    default V computeIfAbsent(K key,
            Function<? super K, ? extends V> mappingFunction) {
        Objects.requireNonNull(mappingFunction);
        V v;
        // 获取map中该key的值,如果为null,则根据返回值判断是否需要put
        if ((v = get(key)) == null) {
            V newValue;
            // 返回值不为null,把该值put到map里面
            if ((newValue = mappingFunction.apply(key)) != null) {
                put(key, newValue);
                return newValue;
            }
        }
        // 返回map中该key的value
        return v;
    }


    // 示例
        Map<String, String> map = new HashMap<>();
        map.put("2", "3");
        map.put("4", "4");
        map.put("5", "0");
        map.computeIfAbsent("2", new Function<String, String>() {
            @Override
            public String apply(String s) {
                if (s.equals("3")) {
                    return "5";
                }
                return "4";
            }
        });
        System.out.println(map.get("2"));
        map.computeIfAbsent("3", new Function<String, String>() {
            @Override
            public String apply(String s) {
                if (s.equals("3")) {
                    return "5";
                }
                return "4";
            }
        });
        System.out.println(map.get("3"));
        System.out.println(map.toString());

输出结果:
3
5
{2=3, 3=5, 4=4, 5=0}

从源码与示例中可以看出

  • 如果该key在HashMap中存在value,则不处理
  • 如果HashMap中不存在该key的value或者value为null,则根据返回值进行处理,返回值不为null,进行put;反之,不处理。

computeIfPresent方法使用

    default V computeIfPresent(K key,
            BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
        Objects.requireNonNull(remappingFunction);
        V oldValue;
        // 该key的value在HashMap中不为null
        if ((oldValue = get(key)) != null) {
            // 获取apply里面的返回值
            V newValue = remappingFunction.apply(key, oldValue);
            if (newValue != null) {
                // 如果返回值不为null,则put
                put(key, newValue);
                return newValue;
            } else {
                // 返回值为null,移除
                remove(key);
                return null;
            }
        } else {
            // 不处理
            return null;
        }
    }

    // 示例
        Map<String, String> map = new HashMap<>();
        map.put("2", "3");
        map.put("4", "4");
        map.put("5", "0");
        map.computeIfPresent("2", new BiFunction<String, String, String>() {
            @Override
            public String apply(String s, String s2) {
                return null;
            }
        });
        System.out.println(map.get("2"));
        map.computeIfPresent("4", new BiFunction<String, String, String>() {
            @Override
            public String apply(String s, String s2) {
                return "44";
            }
        });
        System.out.println(map.get("4"));
        map.computeIfPresent("6", new BiFunction<String, String, String>() {
            @Override
            public String apply(String s, String s2) {
                return "66";
            }
        });
        System.out.println(map.get("6"));
        System.out.println(map.toString());

结果输出:
null
44
null
{4=44, 5=0}
{4=44, 5=0}

get方法分析

    public V get(Object key) {
        Node<K,V> e;
        // 如果不存在,返回null,反之,返回该key的value
        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;
        // HashMap不为null并且长度大于0,还有第一个节点不为null,进行数据查找;反之返回null
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            // 判断第一个节点是不是需要查找的key
            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;
    }

上面就是HashMap主要的源码解析,根据源码,对面试中相关的问题也都能进行作答了,后面再收集一下HashMap相关的面试题。 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值