HashMap源码学习(基于jdk1.8)

本文详细探讨了HashMap在JDK1.8中的实现,包括默认容量、最大容量、负载因子和树化阈值等关键参数。文章分析了Node内部类,并提出疑问为何需要传入hash值。解释了节点拆分算法,提到了链表到红黑树的转换,虽然这部分代码复杂,但能提升数据访问效率。此外,还提到了JDK1.8新增的接口和动态处理key-value的能力,以及红黑树如何优化冲突处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==
HashMap数据结构示意图

//默认初始化容量,必须是2的幂次

static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;


//最大容量,如果指定其它较大值时,则必须是2的幂次,且小于等于1<<30

static final int MAXIMUM_CAPACITY = 1 << 30;


//默认负载因子

static final float DEFAULT_LOAD_FACTOR = 0.75f;


//树化结构最小链节点数,即单个表节点上的链节点超过8个时才会转换为红黑树进行存储

static final int TREEIFY_THRESHOLD = 8;


//树结构转为链结构时的树节点数,即与上面的参数相对应

static final int UNTREEIFY_THRESHOLD = 6;


//树化结构的最小表节点数,即小于这个数时,不会进行链表转红黑树,而是给表扩容

static final int MIN_TREEIFY_CAPACITY = 64;

内部类Node<K,V>不再赘述,比较简单

/*
* 计算node在map中存取时使用的hash值
*/
    static final int hash(Object key) {
        int h;
        //当key不为null时,将key的hashcode的前16位和后16位做异计算返回
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
/*
* 判断若x实现了Comparable<C>接口,则返回x的类型,否则返回空
*/

    static Class<?> comparableClassFor(Object x) {
        if (x instanceof Comparable) {
            Class<?> c; Type[] ts, as; Type t; ParameterizedType p;
            if ((c = x.getClass()) == String.class) // bypass checks
                return c;
            if ((ts = c.getGenericInterfaces()) != null) {
                for (int i = 0; i < ts.length; ++i) {
                    if (((t = ts[i]) instanceof ParameterizedType) &&
                        ((p = (ParameterizedType)t).getRawType() ==
                         Comparable.class) &&
                        (as = p.getActualTypeArguments()) != null &&
                        as.length == 1 && as[0] == c) // type arg is c
                        return c;
                }
            }
        }
        return null;
    }
/*
* 若x为空或者不是kc类型则返回0,否则返回x和k的对比值
*/

    static int compareComparables(Class<?> kc, Object k, Object x) {
        return (x == null || x.getClass() != kc ? 0 :
                ((Comparable)k).compareTo(x));
    }
/*
* 计算返回table的size,结果值为大于或等于cap的最小2的幂次
*/

    static final int tableSizeFor(int cap) {
// 计算前减1,防止cap已经是2的幂次时获取的值为cap*2
        int n = cap - 1;
//以下操作即将cap的二进制值后续值全部补1,如01000010,则补充后为01111111
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
//返回计算值+1,得到大于等于cap的最小2幂次值
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }
// 存储链/树的表格,首次使用时初始化大小,且大小必须为2的幂次
    transient Node<K,V>[] table;
//存储值的集合,用于keySet() 和 values()方法
    transient Set<Map.Entry<K,V>> entrySet;
// hashmap实际存储的节点数,put或remove等操作时都会更新
    transient int size;
//每次成功调整hashmap结构时增加一次,主要用于防止在map上建立子视图时进行调整结构操作
    transient int modCount;
// 要调整hash表大小的下一个大小值(容量*负载因子)
    int threshold;
//哈希表的加载因子
    final float loadFactor;
/*
* 带初始化容量和负载因子的构造函数
*/
    public HashMap(int initialCapacity, float loadFactor) {
        //初始容量入参小于0时抛出异常
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        //初始容量入参大于最大容量时,使用最大容量(1<<30)
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        //负载因子入参小于等于0或者为空时,抛出异常
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        this.loadFactor = loadFactor;
        //hash表调整大小的阙值为大于等于初始容量入参的最小2幂次(不应该是容量*负载因子吗?)
        this.threshold = tableSizeFor(initialCapacity);
    }
//带初始化容量入参的构造函数
    public HashMap(int initialCapacity) {
//使用默认负载因子0.75f构造hashmap
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }
//不带入参的构造函数
    public HashMap() {
//负载因子使用默认值0.75f
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

-------- 由此可见,hashmap的以上构造函数只是确认了负载因子和阙值,并没有做初始化hash表等其它事情

//映射一个已有map的构造函数,负载因子使用默认值0.75f
    public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }
//将已有map对象全量加载到当前hashmap下
    final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
//这里需要注意,如果m为null则会抛空指针
        int s = m.size();
//m大小为空时,直接返回
        if (s > 0) {
//如果table未初始化
            if (table == null) { // pre-size
//按现hashmap的负载因子计算阙值(+1.0f是为了防止计算得到小数时,最后转为int时小于原址)
                float ft = ((float)s / loadFactor) + 1.0F;
                int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                         (int)ft : MAXIMUM_CAPACITY);
//当m计算出的阙值大于原阙值时,重新计算阙值大小
                if (t > threshold)
                    threshold = tableSizeFor(t);
            }
//当m的size大于当前阙值时,调整大小
            else if (s > threshold)
                resize();
            for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
                K key = e.getKey();
                V value = e.getValue();
//按循环put各个对象
                putVal(hash(key), key, value, false, evict);
            }
        }
    }
//返回hashmap内entry个数

    public int size() {
        return size;
    }

//判断hashmap内是否为空
    public boolean isEmpty() {
        return size == 0;
    }
/*
*hashmap的判空用isEmpty和size()==0逻辑上是一致,但是其它map实现类未必,所以map判空时尽量使用isEmpty()
*/
//从hashmap中取出相应key的value,不存在是返回null。主要学习getNode的逻辑
    public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }
//根据hashcode和key对象获取对应node对象
    final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
//table不为空,且对应hash位上的首节点不为null时
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
//首节点hashcode相同且(首节点key与入参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)
//若对应桶内为树结构,则走getTreeNode方法
                    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;
    }

----- 对于该方法存在一点疑义,为什么hash值要作为入参,而不在getNode内直接调用hash(key),否则反而多了hash入参和实际hash(key)不同的可能。

//是否含有对于key值,直接走getNode,不需要过多理解
    public boolean containsKey(Object key) {
        return getNode(hash(key), key) != null;
    }
//向hashmap内存入对象,该种方式会覆盖已有key的value
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
// 将value按key存入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;
//当当前table为空,即未初始化时,调整table大小
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
//计算hash值对应桶内是否已经有node,若没有则按入参创建并赋值到对应桶内
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
//判断首节点是否与存入节点的key值相同,若是则获取首节点
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
//判断是否为树节点,此处和getNode逻辑类似
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
//循环查找链表下是否存在相同key,若不存在则在链表尾部增加该节点,并判断是否需要转为树结构
                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中存在相同key的值,则判断是否替换,无论是否替换返回原值
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
//若hashmap中不存在相同key的值,则增加modcount和size,并判断是否超过阙值需要重新调整大小
        ++modCount;
        if (++size > threshold)
            resize();
//节点插入后调用,开放节后用于继承类特殊实现
        afterNodeInsertion(evict);
        return null;
    }
//重新调整table大小,十分重要的方法
    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) {
//当当前容量已经为最大容量时,修改阙值为最大整数并返回旧表(已经最大,无法再扩大
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
//先将设置新容量=旧容量*2,若新容量小于最大容量且旧容量大于等于默认初始化容量,则新阙值=旧阙值*2
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
//旧容量为0(即未初始化),但旧阙值大于0时,新容量=旧阙值
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults
//旧容量为0,旧阙值为0 则取默认容量和默认阙值(默认容量*默认负载因子
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
//新阙值为0时(从上面的代码来看只有oldCap> MAXIMUM_CAPACITY /2 或者 0<oldCap<DEFAULT_INITIAL_CAPACITY 或者oldCap=0且oldThr > 0
//但oldCap是2的幂次,前面判断oldCap>=MAXIMUM_CAPACITY不成立,所以此处oldCap最大为MAXIMUM_CAPACITY /2
//因此只有0<oldCap<DEFAULT_INITIAL_CAPACITY 或者 oldCap=0且oldThr > 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"})
        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;
//若桶内只有单个节点,则计算新的hash位并存入对应节点
                    if (e.next == null)
                        newTab[e.hash & (newCap - 1)] = e;
                    else if (e instanceof TreeNode)
//若为树节点,则调用split去拆取节点内容
                        ((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;
//将原先同一个hash桶上的节点拆分到newTab[oldIndex]和newTab[oldIndex+oldCap]上
                            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;
    }

---- 其中将老节点拆分到新的hash桶中的算法一开始没理解,最后根据这里的解释理解了e.hash&oldCap==0的算法逻辑

//将桶内指定hash位链表转换为树结构,若桶容量小于最小树化容量时,用resize代替

    final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
//当容量小于最小树化容量时,直接调用resize
        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);
        }
    }

------ 链表转红黑树结构相关的代码等看到以后再解析,瞥了一眼发现套了好几层。

//将m内对象全部存入当前hashMap,其中m不能为null
    public void putAll(Map<? extends K, ? extends V> m) {
        putMapEntries(m, true);
    }
//移除key对应节点,并返回节点的值,若不存在节点则返回null

    public V remove(Object key) {
        Node<K,V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
            null : e.value;
    }
//移除对应hash值,对应key的节点
//当matchValue入参为true时,移除节点对应的value必须与传入的value一致时才移除
//movable仅针对树结构,当为true时,移除相应节点后需要调整其它节点位置

    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;
//判断map是否已经初始化或者是否存在对应的hash值
        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 {
//链表结构时,迭代获取符合key的节点
                    do {
                        if (e.hash == hash &&
                            ((k = e.key) == key ||
                             (key != null && key.equals(k)))) {
                            node = e;
                            break;
                        }
                        p = e;
                    } while ((e = e.next) != null);
                }
            }
//节点存在时,同时根据matchValue判断是否需要校验值
            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;
//增加操作计数并减少size大小
                ++modCount;
                --size;
//调用开放的移除节点后方法
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }

中间刷了几天的leetcode没有更新博客,现在继续//

//清除hashmap内所有值
    public void clear() {
        Node<K,V>[] tab;
//增加操作计数
        modCount++;
        if ((tab = table) != null && size > 0) {
//清零size 并迭代清空桶内数据
            size = 0;
            for (int i = 0; i < tab.length; ++i)
                tab[i] = null;
        }
    }
// 查询是否包含对应value
    public boolean containsValue(Object value) {
        Node<K,V>[] tab; V v;
// 迭代循环判断值相等
        if ((tab = table) != null && size > 0) {
            for (int i = 0; i < tab.length; ++i) {
                for (Node<K,V> e = tab[i]; e != null; e = e.next) {
                    if ((v = e.value) == value ||
                        (value != null && value.equals(v)))
                        return true;
                }
            }
        }
        return false;
    }
//返回hashmap key集合的视图

    public Set<K> keySet() {
        Set<K> ks = keySet;
        if (ks == null) {
            ks = new KeySet();
            keySet = ks;
        }
        return ks;
    }

    final class KeySet extends AbstractSet<K> {
        public final int size()                 { return size; }
        public final void clear()               { HashMap.this.clear(); }
        public final Iterator<K> iterator()     { return new KeyIterator(); }
        public final boolean contains(Object o) { return containsKey(o); }
        public final boolean remove(Object key) {
            return removeNode(hash(key), key, null, false, true) != null;
        }
        public final Spliterator<K> spliterator() {
            return new KeySpliterator<>(HashMap.this, 0, -1, 0, 0);
        }
        public final void forEach(Consumer<? super K> action) {
            Node<K,V>[] tab;
            if (action == null)
                throw new NullPointerException();
            if (size > 0 && (tab = table) != null) {
//循环前获取hashmap的操作计数,防止在循环过程中hashmap进行相应操作,而视图还是按老key集操作
                int mc = modCount;
                for (int i = 0; i < tab.length; ++i) {
                    for (Node<K,V> e = tab[i]; e != null; e = e.next)
                        action.accept(e.key);
                }
                if (modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }
    }
//返回hashmap value的集合视图
    public Collection<V> values() {
        Collection<V> vs = values;
        if (vs == null) {
            vs = new Values();
            values = vs;
        }
        return vs;
    }

    final class Values extends AbstractCollection<V> {
        public final int size()                 { return size; }
        public final void clear()               { HashMap.this.clear(); }
        public final Iterator<V> iterator()     { return new ValueIterator(); }
        public final boolean contains(Object o) { return containsValue(o); }
        public final Spliterator<V> spliterator() {
            return new ValueSpliterator<>(HashMap.this, 0, -1, 0, 0);
        }
        public final void forEach(Consumer<? super V> action) {
            Node<K,V>[] tab;
            if (action == null)
                throw new NullPointerException();
            if (size > 0 && (tab = table) != null) {
                int mc = modCount;
                for (int i = 0; i < tab.length; ++i) {
                    for (Node<K,V> e = tab[i]; e != null; e = e.next)
                        action.accept(e.value);
                }
                if (modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }
    }
//返回hashmap 键值对的集合视图
    public Set<Map.Entry<K,V>> entrySet() {
        Set<Map.Entry<K,V>> es;
        return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
    }

    final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
        public final int size()                 { return size; }
        public final void clear()               { HashMap.this.clear(); }
        public final Iterator<Map.Entry<K,V>> iterator() {
            return new EntryIterator();
        }
        public final boolean contains(Object o) {
            if (!(o instanceof Map.Entry))
                return false;
            Map.Entry<?,?> e = (Map.Entry<?,?>) o;
            Object key = e.getKey();
            Node<K,V> candidate = getNode(hash(key), key);
            return candidate != null && candidate.equals(e);
        }
        public final boolean remove(Object o) {
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>) o;
                Object key = e.getKey();
                Object value = e.getValue();
                return removeNode(hash(key), key, value, true, true) != null;
            }
            return false;
        }
        public final Spliterator<Map.Entry<K,V>> spliterator() {
            return new EntrySpliterator<>(HashMap.this, 0, -1, 0, 0);
        }
        public final void forEach(Consumer<? super Map.Entry<K,V>> action) {
            Node<K,V>[] tab;
            if (action == null)
                throw new NullPointerException();
            if (size > 0 && (tab = table) != null) {
                int mc = modCount;
                for (int i = 0; i < tab.length; ++i) {
                    for (Node<K,V> e = tab[i]; e != null; e = e.next)
                        action.accept(e);
                }
                if (modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }
    }

-------- 以上三个方法均为获取相应的视图,内容会随hashmap本体对象改变而改变。同时返回的对象也提供了相应的操作方法。

------- 以下为jdk1.8新增接口的实现方法

//获取相应key的value,若不存在则返回默认值
    public V getOrDefault(Object key, V defaultValue) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? defaultValue : e.value;
    }
//仅在该key值不存在value时,将增加该键值对
    public V putIfAbsent(K key, V value) {
        return putVal(hash(key), key, value, true, true);
    }
//当存在该key,且值为给定value时,移除该节点。成功移除返回true,否则返回false
    public boolean remove(Object key, Object value) {
        return removeNode(hash(key), key, value, true, true) != null;
    }
//若存在key,且只为oldValue,将值更新为newValue。需要注意的是该操作不改变modCount
    public boolean replace(K key, V oldValue, V newValue) {
        Node<K,V> e; V v;
        if ((e = getNode(hash(key), key)) != null &&
            ((v = e.value) == oldValue || (v != null && v.equals(oldValue)))) {
            e.value = newValue;
            afterNodeAccess(e);
            return true;
        }
        return false;
    }
//若存在key对应的值,则替换为value,不更改modCount
    public V replace(K key, V value) {
        Node<K,V> e;
        if ((e = getNode(hash(key), key)) != null) {
            V oldValue = e.value;
            e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
        return null;
    }
//查看是否存在key对应值,若不存在则通过mappingFunction计算并录入值,最终返回key对应value
    public V computeIfAbsent(K key,
                             Function<? super K, ? extends V> mappingFunction) {
//匹配方法为空时返回空指针
        if (mappingFunction == null)
            throw new NullPointerException();
        int hash = hash(key);
        Node<K,V>[] tab; Node<K,V> first; int n, i;
        int binCount = 0;
        TreeNode<K,V> t = null;
        Node<K,V> old = null;
//tab未初始化时先初始化tab
        if (size > threshold || (tab = table) == null ||
            (n = tab.length) == 0)
            n = (tab = resize()).length;
//获取对应key所在桶的首节点(这边没有像之前代码一样先匹配首节点)
        if ((first = tab[i = (n - 1) & hash]) != null) {
            if (first instanceof TreeNode)
//从树结构获取匹配节点
                old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key);
            else {
                Node<K,V> e = first; K k;
                do {
//从链表结构获取匹配节点,并记录节点数
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k)))) {
                        old = e;
                        break;
                    }
                    ++binCount;
                } while ((e = e.next) != null);
            }
            V oldValue;
//若存在符合的节点,且节点值不为空,则直接返回旧值
            if (old != null && (oldValue = old.value) != null) {
                afterNodeAccess(old);
                return oldValue;
            }
        }
//否则通过匹配方法计算匹配新值
        V v = mappingFunction.apply(key);
//匹配值为空时直接返回空值
        if (v == null) {
            return null;
        } else if (old != null) {
//旧节点存在但值为null时赋值v
            old.value = v;
            afterNodeAccess(old);
            return v;
        }
//新增节点,并修改size和modCount
        else if (t != null)
            t.putTreeVal(this, tab, hash, key, v);
        else {
            tab[i] = newNode(hash, key, v, first);
            if (binCount >= TREEIFY_THRESHOLD - 1)
                treeifyBin(tab, hash);
        }
        ++modCount;
        ++size;
        afterNodeInsertion(true);
        return v;
    }
//与computeIfAbsent相反,该方法是判断key对应value是否存在,若存在则根据remappingFunction计算替换旧值,若不存在则不处理
    public V computeIfPresent(K key,
                              BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
//remappingFunction 为空时,抛出空指针异常
        if (remappingFunction == null)
            throw new NullPointerException();
        Node<K,V> e; V oldValue;
        int hash = hash(key);
//key存在,且旧值不为null时
        if ((e = getNode(hash, key)) != null &&
            (oldValue = e.value) != null) {
//根据旧值和key计算新值
            V v = remappingFunction.apply(key, oldValue);
//新值不为空则替换旧值,为空则移除节点
            if (v != null) {
                e.value = v;
                afterNodeAccess(e);
                return v;
            }
            else
                removeNode(hash, key, null, false, true);
        }
        return null;
    }
//算是前两个方法的结合吧
//若存在key,则计算替换新值(新值为null则移除节点
//若不存在key,且计算新值不为null,则新增节点
    public V compute(K key,
                     BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
//计算匹配方法为空则抛出空指针异常
        if (remappingFunction == null)
            throw new NullPointerException();
        int hash = hash(key);
        Node<K,V>[] tab; Node<K,V> first; int n, i;
        int binCount = 0;
        TreeNode<K,V> t = null;
        Node<K,V> old = null;
//tab未初始化则先初始化tab
        if (size > threshold || (tab = table) == null ||
            (n = tab.length) == 0)
            n = (tab = resize()).length;
//检查匹配key值对应node节点
        if ((first = tab[i = (n - 1) & hash]) != null) {
            if (first instanceof TreeNode)
                old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key);
            else {
                Node<K,V> e = first; K k;
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k)))) {
                        old = e;
                        break;
                    }
                    ++binCount;
                } while ((e = e.next) != null);
            }
        }
//获取旧值并计算新值
        V oldValue = (old == null) ? null : old.value;
        V v = remappingFunction.apply(key, oldValue);
//原节点存在时替换新值或者移除节点(新值为null时移除节点
        if (old != null) {
            if (v != null) {
                old.value = v;
                afterNodeAccess(old);
            }
            else
                removeNode(hash, key, null, false, true);
        }
//原节点不存在且新值不为null时,增加新节点
        else if (v != null) {
            if (t != null)
                t.putTreeVal(this, tab, hash, key, v);
            else {
                tab[i] = newNode(hash, key, v, first);
                if (binCount >= TREEIFY_THRESHOLD - 1)
                    treeifyBin(tab, hash);
            }
            ++modCount;
            ++size;
            afterNodeInsertion(true);
        }
        return v;
    }
//根据key去查找node
//若node存在,且oldValue不为null,则根据oldValue和value通过remappingFunction计算新值v,v为null时移除节点
//若node存在,但oldValue为null,则替换为value
//若node不存在,则新值值为value的节点
    public V merge(K key, V value,
                   BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
//value或remappingFunction为空时抛出空指针
        if (value == null)
            throw new NullPointerException();
        if (remappingFunction == null)
            throw new NullPointerException();
        int hash = hash(key);
        Node<K,V>[] tab; Node<K,V> first; int n, i;
        int binCount = 0;
        TreeNode<K,V> t = null;
        Node<K,V> old = null;
//若tab未初始化,初始化tab
        if (size > threshold || (tab = table) == null ||
            (n = tab.length) == 0)
            n = (tab = resize()).length;
//查找key对应node
        if ((first = tab[i = (n - 1) & hash]) != null) {
            if (first instanceof TreeNode)
                old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key);
            else {
                Node<K,V> e = first; K k;
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k)))) {
                        old = e;
                        break;
                    }
                    ++binCount;
                } while ((e = e.next) != null);
            }
        }

        if (old != null) {
            V v;
//node不为null,且oldValue不为null时,根据oldValue和value计算新值v
            if (old.value != null)
                v = remappingFunction.apply(old.value, value);
            else
//否则使用value作为新值并替换旧值
                v = value;
            if (v != null) {
                old.value = v;
                afterNodeAccess(old);
            }
            else
//v为null时移除节点,仅存在于remappingFunction.apply(old.value, value)结果为null的情况
                removeNode(hash, key, null, false, true);
            return v;
        }
//node不存在时新增key-value节点(此处value不会为null,应该可以不用判断
        if (value != null) {
            if (t != null)
                t.putTreeVal(this, tab, hash, key, value);
            else {
                tab[i] = newNode(hash, key, value, first);
                if (binCount >= TREEIFY_THRESHOLD - 1)
                    treeifyBin(tab, hash);
            }
            ++modCount;
            ++size;
            afterNodeInsertion(true);
        }
        return value;
    }
//迭代对hashmap内所有的node做action处理
//和EntrySet的forEach方法做法一致
    public void forEach(BiConsumer<? super K, ? super V> action) {
        Node<K,V>[] tab;
        if (action == null)
            throw new NullPointerException();
        if (size > 0 && (tab = table) != null) {
            int mc = modCount;
            for (int i = 0; i < tab.length; ++i) {
                for (Node<K,V> e = tab[i]; e != null; e = e.next)
                    action.accept(e.key, e.value);
            }
            if (modCount != mc)
                throw new ConcurrentModificationException();
        }
    }
//将hashmap内所有的value按function的逻辑重新计算赋值
    public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
        Node<K,V>[] tab;
        if (function == null)
            throw new NullPointerException();
        if (size > 0 && (tab = table) != null) {
            int mc = modCount;
            for (int i = 0; i < tab.length; ++i) {
                for (Node<K,V> e = tab[i]; e != null; e = e.next) {
                    e.value = function.apply(e.key, e.value);
                }
            }
            if (modCount != mc)
                throw new ConcurrentModificationException();
        }
    }

---------- 到此jdk1.8新增的接口都已经列出,发现1.8增加了很多方法用于动态处理key-value,解决了之前只能存取修改静态值的限制。且1.8还加入了红黑树结构用于存储冲突较大的桶,加速了数据读取效率。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值