Should HashMap::computeIfAbsent be considered a "structural modification" for an existing key?

Michael Rasmussen Michael.Rasmussen at roguewave.com
Tue Nov 20 09:41:52 UTC 2018


A quick snippet of code that shows this, by reflecting into the Map to get the table field, and see that it changes:

/* --- snip --- */
package com.test;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.function.Function;

public class Test {
  public static void main(String[] args) throws Exception {
    HashMap<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < 13; i++) {
      map.computeIfAbsent(i, Function.identity());
    }

    Field table = HashMap.class.getDeclaredField("table");
    table.setAccessible(true);
    System.out.println(map.containsKey(1));
    System.out.println(table.get(map));
    map.computeIfAbsent(1, Function.identity());
    System.out.println(table.get(map));
  }
}
/* --- snap --- */
true
[Ljava.util.HashMap$Node;@4cb2c100
[Ljava.util.HashMap$Node;@6fb554cc
/* --- snude --- */


More information about the core-libs-dev mailing list