摘要:本篇涉及少许以下简称新特性,请驴友们系好安全带,准备开车。观光线路图是在中新增的一个方法,相对而言较为陌生。其作用是把的计算结果关联到上即返回值作为新。实际上,乃缩写,即二元函数之意类似。
本文以jdk1.8中HashMap.compute()方法为切入点,分析其中难理解、有价值的源码片段(类似源码查看是ctrl+鼠标左键的过程)。本篇涉及少许Java8(以下简称J8)新特性,请驴友们系好安全带,准备开车。观光线路图:compute() --> BiFunction --> @FunctionalInterface --> afterNodeAccess() --> computeIfAbsent() --> computeIfPresent()...
☞ compute()@Override public V compute(K key, BiFunction super K, ? super V, ? extends V> remappingFunction) { if (remappingFunction == null) throw new NullPointerException(); int hash = hash(key); Node[] tab; Node first; int n, i; int binCount = 0; TreeNode t = null; Node old = null; if (size > threshold || (tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; if ((first = tab[i = (n - 1) & hash]) != null) { if (first instanceof TreeNode) old = (t = (TreeNode )first).getTreeNode(hash, key); else { Node 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); if (old != null) { if (v != null) { old.value = v; afterNodeAccess(old); } else removeNode(hash, key, null, false, true); } 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; }
compute()是java8在Map中新增的一个方法,相对而言较为陌生。其作用是把remappingFunction的计算结果关联到key上(即remappingFunction返回值作为新value)。写一段它的简单应用的代码,并与“同级生”merge()类比加深理解:
HashMap map = new HashMap(); map.put("a", "c"); map.put("b", "h"); map.put("c", "e"); map.compute("a", (k, v) -> "C") ; map.merge("b", "h", (k, v) -> "H") ; map.compute("d", (k, v) -> "D") ; map.merge("c", "e", (k, v) -> null) ; System.out.println(map.toString()); // 输出结果为:{a=C, b=H, d=D}
下面用一张表来总结源码最后的判断对应的操作:
vold | null | not null |
---|---|---|
null | remove | |
not null | put | replace |
/** * Represents a function that accepts two arguments and produces a result. * This is the two-arity specialization of {@link Function}. * *This is a functional interface * whose functional method is {@link #apply(Object, Object)}. * * @param
the type of the first argument to the function * @param the type of the second argument to the function * @param the type of the result of the function * * @see Function * @since 1.8 */ @FunctionalInterface public interface BiFunction { /** * Applies this function to the given arguments. * * @param t the first function argument * @param u the second function argument * @return the function result */ R apply(T t, U u); /** * Returns a composed function that first applies this function to * its input, and then applies the {@code after} function to the result. * If evaluation of either function throws an exception, it is relayed to * the caller of the composed function. * * @param the type of output of the {@code after} function, and of the * composed function * @param after the function to apply after this function is applied * @return a composed function that first applies this function and then * applies the {@code after} function * @throws NullPointerException if after is null */ default BiFunction andThen(Function super R, ? extends V> after) { Objects.requireNonNull(after); return (T t, U u) -> after.apply(apply(t, u)); } }
是的,这也J8新增的梗。当我第一眼看到逼函数(BiFunction)的时候就原地炸了。实际上,“Bi”乃binary缩写,即“二元函数”之意(类似“1+1=2”)。这类接口称为“函数式接口”,可以看出,它的==方法有方法体==。且以“default”修饰符修饰,不影响接口的实现类,算是一种向下兼容吧。
☞ @FunctionalInterface/** * An informative annotation type used to indicate that an interface * type declaration is intended to be a functional interface as * defined by the Java Language Specification. * * Conceptually, a functional interface has exactly one abstract * method. Since {@linkplain java.lang.reflect.Method#isDefault() * default methods} have an implementation, they are not abstract. If * an interface declares an abstract method overriding one of the * public methods of {@code java.lang.Object}, that also does * not count toward the interface"s abstract method count * since any implementation of the interface will have an * implementation from {@code java.lang.Object} or elsewhere. * *Note that instances of functional interfaces can be created with * lambda expressions, method references, or constructor references. * *
If a type is annotated with this annotation type, compilers are * required to generate an error message unless: * *
However, the compiler will treat any interface meeting the * definition of a functional interface as a functional interface * regardless of whether or not a {@code FunctionalInterface} * annotation is present on the interface declaration. * * @jls 4.3.2. The Class Object * @jls 9.8 Functional Interfaces * @jls 9.4.3 Interface Method Body * @since 1.8 */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface FunctionalInterface {}
“@FunctionalInterface”并非必须,就像javascript中的“use strict”,使得编译器能检查该接口是否存在语法错误。此外,从注释还可以看出:
☞ afterNodeAccess()函数接口仅有一个抽象方法;
default方法、Object的重载方法(、静态方法)非抽象方法;
// Callbacks to allow LinkedHashMap post-actions void afterNodeAccess(Nodep) { } void afterNodeInsertion(boolean evict) { } void afterNodeRemoval(Node p) { }
从注释可以看到这是为LinkedHashMap留的后路,不过HashMap存取操作中经常发现他们的身影,即使实现为空。。
☞ computeIfAbsent()/computeIfPresent()@Override public V computeIfAbsent(K key, Function super K, ? extends V> mappingFunction) { if (mappingFunction == null) throw new NullPointerException(); int hash = hash(key); Node[] tab; Node first; int n, i; int binCount = 0; TreeNode t = null; Node old = null; if (size > threshold || (tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; if ((first = tab[i = (n - 1) & hash]) != null) { if (first instanceof TreeNode) old = (t = (TreeNode )first).getTreeNode(hash, key); else { Node 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) { old.value = v; // old.value null afterNodeAccess(old); return v; } 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; } public V computeIfPresent(K key, BiFunction super K, ? super V, ? extends V> remappingFunction) { if (remappingFunction == null) throw new NullPointerException(); Node e; V oldValue; int hash = hash(key); if ((e = getNode(hash, key)) != null && (oldValue = e.value) != null) { 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; }
computeIfAbsent()与computeIfPresent()可以说是compute()的“子集”。
这次的功夫主要花在了学习J8的知识点上,经过前2篇后HashMap本身不再那么可怕。你觉得呢?
更多有意思的内容,欢迎访问笔者小站: rebey.cn
彩蛋最后分享几个学习Java8过程中看到良心网址(以下链接为网站系列文章之一,希望细心的你举一反三):
Java8初体验(二)Stream语法详解;
Java 8 中的 Streams API 详解;
Java 8 flatMap example;
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/70100.html
摘要:如今行至于此,当观赏一方。由于所返回的无执行意义。源码阅读总体门槛相对而言比,毕竟大多数底层都由实现了。比心可通过这篇文章理解创建一个实例过程图工作原理往期线路回顾源码一带一路系列之源码一带一路系列之源码一带一路系列之 本文以jdk1.8中LinkedHashMap.afterNodeAccess()方法为切入点,分析其中难理解、有价值的源码片段(类似源码查看是ctrl+鼠标左键的过程...
摘要:一路至此,风景过半。与虽然名字各异,源码实现基本相同,除了增加了线程安全。同时注意溢出情况处理。同时增加了考虑并发问题。此外,源码中出现了大量泛型如。允许为非线程安全有序。 一路至此,风景过半。ArrayList与Vector虽然名字各异,源码实现基本相同,除了Vector增加了线程安全。所以作者建议我们在不需要线程安全的情况下尽量使用ArrayList。下面看看在ArrayList源...
摘要:同样在源码的与分别见看到老朋友和。这样做可以降低性能消耗的同时,还可以减少序列化字节流的大小,从而减少网络开销框架中。使用了反射来寻找是否声明了这两个方法。十进制和,通过返回值能反应当前状态。 Map篇暂告段落,却并非离我们而去。这不在本篇中你就能经常见到她。HashSet、LinkedHashSet、TreeSet各自基于对应Map实现,各自源码内容较少,因此归纳为一篇。 HashS...
摘要:观光线路图将涉及到的源码全局变量哈希表初始化长度默认值是负载因子默认表示的填满程度。根据是否为零将原链表拆分成个链表,一部分仍保留在原链表中不需要移动,一部分移动到原索引的新链表中。 前言 本文以jdk1.8中HashMap.putAll()方法为切入点,分析其中难理解、有价值的源码片段(类似ctrl+鼠标左键查看的源码过程)。✈观光线路图:putAll() --> putMapEnt...
摘要:表示该类本身不可比表示与对应的之间不可比。当数目满足时,链表将转为红黑树结构,否则继续扩容。至此,插入告一段落。当超出时,哈希表将会即内部数据结构重建至大约两倍。要注意的是使用许多有这相同的键值肯定会降低哈希表性能。 回顾上期✈观光线路图:putAll() --> putMapEntries() --> tableSizeFor() --> resize() --> hash() --...
阅读 2805·2023-04-25 20:06
阅读 1419·2021-08-26 14:15
阅读 2171·2021-08-12 13:27
阅读 1729·2019-08-30 15:55
阅读 3423·2019-08-30 13:20
阅读 2791·2019-08-29 15:12
阅读 3294·2019-08-29 15:06
阅读 2822·2019-08-29 14:13