Should HashMap::computeIfAbsent be considered a "structural modification" for an existing key?
Peter Levart
peter.levart at gmail.com
Tue Nov 20 11:08:11 UTC 2018
Hi Michael,
If in your code you "know" that a particular key must be present, then
why aren't you using .get(key) in that place instead of
.computeIfAbsent() and trying to rely on it being a non-modifying operation?
Note that in some Map implementations (WeakHashMap for example) event
.get(key) may be an (internal structure) modifying operation.
Regards, Peter
On 11/20/18 10:41 AM, Michael Rasmussen wrote:
> 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