资讯专栏INFORMATION COLUMN

【java源码一带一路系列】之HashMap.compute()

wapeyang / 590人阅读

摘要:本篇涉及少许以下简称新特性,请驴友们系好安全带,准备开车。观光线路图是在中新增的一个方法,相对而言较为陌生。其作用是把的计算结果关联到上即返回值作为新。实际上,乃缩写,即二元函数之意类似。

本文以jdk1.8中HashMap.compute()方法为切入点,分析其中难理解、有价值的源码片段(类似源码查看是ctrl+鼠标左键的过程)。本篇涉及少许Java8(以下简称J8)新特性,请驴友们系好安全带,准备开车。观光线路图:compute() --> BiFunction --> @FunctionalInterface --> afterNodeAccess() --> computeIfAbsent() --> computeIfPresent()...

☞ compute()

</>复制代码

  1. @Override
  2. public V compute(K key,
  3. BiFunction remappingFunction) {
  4. if (remappingFunction == null)
  5. throw new NullPointerException();
  6. int hash = hash(key);
  7. Node[] tab; Node first; int n, i;
  8. int binCount = 0;
  9. TreeNode t = null;
  10. Node old = null;
  11. if (size > threshold || (tab = table) == null ||
  12. (n = tab.length) == 0)
  13. n = (tab = resize()).length;
  14. if ((first = tab[i = (n - 1) & hash]) != null) {
  15. if (first instanceof TreeNode)
  16. old = (t = (TreeNode)first).getTreeNode(hash, key);
  17. else {
  18. Node e = first; K k;
  19. do {
  20. if (e.hash == hash &&
  21. ((k = e.key) == key || (key != null && key.equals(k)))) {
  22. old = e;
  23. break;
  24. }
  25. ++binCount;
  26. } while ((e = e.next) != null);
  27. }
  28. }
  29. V oldValue = (old == null) ? null : old.value;
  30. V v = remappingFunction.apply(key, oldValue);
  31. if (old != null) {
  32. if (v != null) {
  33. old.value = v;
  34. afterNodeAccess(old);
  35. }
  36. else
  37. removeNode(hash, key, null, false, true);
  38. }
  39. else if (v != null) {
  40. if (t != null)
  41. t.putTreeVal(this, tab, hash, key, v);
  42. else {
  43. tab[i] = newNode(hash, key, v, first);
  44. if (binCount >= TREEIFY_THRESHOLD - 1)
  45. treeifyBin(tab, hash);
  46. }
  47. ++modCount;
  48. ++size;
  49. afterNodeInsertion(true);
  50. }
  51. return v;
  52. }

compute()是java8在Map中新增的一个方法,相对而言较为陌生。其作用是把remappingFunction的计算结果关联到key上(即remappingFunction返回值作为新value)。写一段它的简单应用的代码,并与“同级生”merge()类比加深理解:

</>复制代码

  1. HashMap map = new HashMap();
  2. map.put("a", "c");
  3. map.put("b", "h");
  4. map.put("c", "e");
  5. map.compute("a", (k, v) -> "C") ;
  6. map.merge("b", "h", (k, v) -> "H") ;
  7. map.compute("d", (k, v) -> "D") ;
  8. map.merge("c", "e", (k, v) -> null) ;
  9. System.out.println(map.toString());
  10. // 输出结果为:{a=C, b=H, d=D}

下面用一张表来总结源码最后的判断对应的操作:

vold null not null
null remove
not null put replace
☞ BiFunction

</>复制代码

  1. /**
  2. * Represents a function that accepts two arguments and produces a result.
  3. * This is the two-arity specialization of {@link Function}.
  4. *
  5. *

    This is a functional interface

  6. * whose functional method is {@link #apply(Object, Object)}.
  7. *
  8. * @param the type of the first argument to the function
  9. * @param the type of the second argument to the function
  10. * @param the type of the result of the function
  11. *
  12. * @see Function
  13. * @since 1.8
  14. */
  15. @FunctionalInterface
  16. public interface BiFunction {
  17. /**
  18. * Applies this function to the given arguments.
  19. *
  20. * @param t the first function argument
  21. * @param u the second function argument
  22. * @return the function result
  23. */
  24. R apply(T t, U u);
  25. /**
  26. * Returns a composed function that first applies this function to
  27. * its input, and then applies the {@code after} function to the result.
  28. * If evaluation of either function throws an exception, it is relayed to
  29. * the caller of the composed function.
  30. *
  31. * @param the type of output of the {@code after} function, and of the
  32. * composed function
  33. * @param after the function to apply after this function is applied
  34. * @return a composed function that first applies this function and then
  35. * applies the {@code after} function
  36. * @throws NullPointerException if after is null
  37. */
  38. default BiFunction andThen(Function after) {
  39. Objects.requireNonNull(after);
  40. return (T t, U u) -> after.apply(apply(t, u));
  41. }
  42. }

是的,这也J8新增的梗。当我第一眼看到逼函数(BiFunction)的时候就原地炸了。实际上,“Bi”乃binary缩写,即“二元函数”之意(类似“1+1=2”)。这类接口称为“函数式接口”,可以看出,它的==方法有方法体==。且以“default”修饰符修饰,不影响接口的实现类,算是一种向下兼容吧。

☞ @FunctionalInterface

</>复制代码

  1. /**
  2. * An informative annotation type used to indicate that an interface
  3. * type declaration is intended to be a functional interface as
  4. * defined by the Java Language Specification.
  5. *
  6. * Conceptually, a functional interface has exactly one abstract
  7. * method. Since {@linkplain java.lang.reflect.Method#isDefault()
  8. * default methods} have an implementation, they are not abstract. If
  9. * an interface declares an abstract method overriding one of the
  10. * public methods of {@code java.lang.Object}, that also does
  11. * not count toward the interface"s abstract method count
  12. * since any implementation of the interface will have an
  13. * implementation from {@code java.lang.Object} or elsewhere.
  14. *
  15. *

    Note that instances of functional interfaces can be created with

  16. * lambda expressions, method references, or constructor references.
  17. *
  18. *

    If a type is annotated with this annotation type, compilers are

  19. * required to generate an error message unless:
  20. *
  21. *

    • *
    • The type is an interface type and not an annotation type, enum, or class.
    • *
    • The annotated type satisfies the requirements of a functional interface.
    • *
  22. *
  23. *

    However, the compiler will treat any interface meeting the

  24. * definition of a functional interface as a functional interface
  25. * regardless of whether or not a {@code FunctionalInterface}
  26. * annotation is present on the interface declaration.
  27. *
  28. * @jls 4.3.2. The Class Object
  29. * @jls 9.8 Functional Interfaces
  30. * @jls 9.4.3 Interface Method Body
  31. * @since 1.8
  32. */
  33. @Documented
  34. @Retention(RetentionPolicy.RUNTIME)
  35. @Target(ElementType.TYPE)
  36. public @interface FunctionalInterface {}

“@FunctionalInterface”并非必须,就像javascript中的“use strict”,使得编译器能检查该接口是否存在语法错误。此外,从注释还可以看出:

</>复制代码

  1. 函数接口仅有一个抽象方法;

  2. default方法、Object的重载方法(、静态方法)非抽象方法;

☞ afterNodeAccess()

</>复制代码

  1. // Callbacks to allow LinkedHashMap post-actions
  2. void afterNodeAccess(Node p) { }
  3. void afterNodeInsertion(boolean evict) { }
  4. void afterNodeRemoval(Node p) { }

从注释可以看到这是为LinkedHashMap留的后路,不过HashMap存取操作中经常发现他们的身影,即使实现为空。。

☞ computeIfAbsent()/computeIfPresent()

</>复制代码

  1. @Override
  2. public V computeIfAbsent(K key,
  3. Function mappingFunction) {
  4. if (mappingFunction == null)
  5. throw new NullPointerException();
  6. int hash = hash(key);
  7. Node[] tab; Node first; int n, i;
  8. int binCount = 0;
  9. TreeNode t = null;
  10. Node old = null;
  11. if (size > threshold || (tab = table) == null ||
  12. (n = tab.length) == 0)
  13. n = (tab = resize()).length;
  14. if ((first = tab[i = (n - 1) & hash]) != null) {
  15. if (first instanceof TreeNode)
  16. old = (t = (TreeNode)first).getTreeNode(hash, key);
  17. else {
  18. Node e = first; K k;
  19. do {
  20. if (e.hash == hash &&
  21. ((k = e.key) == key || (key != null && key.equals(k)))) {
  22. old = e;
  23. break;
  24. }
  25. ++binCount;
  26. } while ((e = e.next) != null);
  27. }
  28. V oldValue;
  29. if (old != null && (oldValue = old.value) != null) {
  30. afterNodeAccess(old);
  31. return oldValue;
  32. }
  33. }
  34. V v = mappingFunction.apply(key);
  35. if (v == null) {
  36. return null;
  37. } else if (old != null) {
  38. old.value = v; // old.value null
  39. afterNodeAccess(old);
  40. return v;
  41. }
  42. else if (t != null)
  43. t.putTreeVal(this, tab, hash, key, v);
  44. else {
  45. tab[i] = newNode(hash, key, v, first);
  46. if (binCount >= TREEIFY_THRESHOLD - 1)
  47. treeifyBin(tab, hash);
  48. }
  49. ++modCount;
  50. ++size;
  51. afterNodeInsertion(true);
  52. return v;
  53. }
  54. public V computeIfPresent(K key,
  55. BiFunction remappingFunction) {
  56. if (remappingFunction == null)
  57. throw new NullPointerException();
  58. Node e; V oldValue;
  59. int hash = hash(key);
  60. if ((e = getNode(hash, key)) != null &&
  61. (oldValue = e.value) != null) {
  62. V v = remappingFunction.apply(key, oldValue);
  63. if (v != null) {
  64. e.value = v;
  65. afterNodeAccess(e);
  66. return v;
  67. }
  68. else
  69. removeNode(hash, key, null, false, true);
  70. }
  71. return null;
  72. }

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

相关文章

  • java源码一带一路系列LinkedHashMap.afterNodeAccess()

    摘要:如今行至于此,当观赏一方。由于所返回的无执行意义。源码阅读总体门槛相对而言比,毕竟大多数底层都由实现了。比心可通过这篇文章理解创建一个实例过程图工作原理往期线路回顾源码一带一路系列之源码一带一路系列之源码一带一路系列之 本文以jdk1.8中LinkedHashMap.afterNodeAccess()方法为切入点,分析其中难理解、有价值的源码片段(类似源码查看是ctrl+鼠标左键的过程...

    levy9527 评论0 收藏0
  • java源码一带一路系列ArrayList

    摘要:一路至此,风景过半。与虽然名字各异,源码实现基本相同,除了增加了线程安全。同时注意溢出情况处理。同时增加了考虑并发问题。此外,源码中出现了大量泛型如。允许为非线程安全有序。 一路至此,风景过半。ArrayList与Vector虽然名字各异,源码实现基本相同,除了Vector增加了线程安全。所以作者建议我们在不需要线程安全的情况下尽量使用ArrayList。下面看看在ArrayList源...

    RebeccaZhong 评论0 收藏0
  • java源码一带一路系列HashSet、LinkedHashSet、TreeSet

    摘要:同样在源码的与分别见看到老朋友和。这样做可以降低性能消耗的同时,还可以减少序列化字节流的大小,从而减少网络开销框架中。使用了反射来寻找是否声明了这两个方法。十进制和,通过返回值能反应当前状态。 Map篇暂告段落,却并非离我们而去。这不在本篇中你就能经常见到她。HashSet、LinkedHashSet、TreeSet各自基于对应Map实现,各自源码内容较少,因此归纳为一篇。 HashS...

    UCloud 评论0 收藏0
  • java源码一带一路系列HashMap.putAll()

    摘要:观光线路图将涉及到的源码全局变量哈希表初始化长度默认值是负载因子默认表示的填满程度。根据是否为零将原链表拆分成个链表,一部分仍保留在原链表中不需要移动,一部分移动到原索引的新链表中。 前言 本文以jdk1.8中HashMap.putAll()方法为切入点,分析其中难理解、有价值的源码片段(类似ctrl+鼠标左键查看的源码过程)。✈观光线路图:putAll() --> putMapEnt...

    chanjarster 评论0 收藏0
  • java源码一带一路系列HashMap.putVal()

    摘要:表示该类本身不可比表示与对应的之间不可比。当数目满足时,链表将转为红黑树结构,否则继续扩容。至此,插入告一段落。当超出时,哈希表将会即内部数据结构重建至大约两倍。要注意的是使用许多有这相同的键值肯定会降低哈希表性能。 回顾上期✈观光线路图:putAll() --> putMapEntries() --> tableSizeFor() --> resize() --> hash() --...

    cloud 评论0 收藏0

发表评论

0条评论

wapeyang

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<