Skip to content

putIfAbsent should replace a null value  #280

Open
@ben-manes

Description

@ben-manes

This was shown in a recent Java Collections Puzzlers. The JavaDoc for Map.putIfAbsent states the following.

If the specified key is not already associated with a value (or is mapped to {@code null}) associates it with the given value and returns {@code null}, else returns the current value.

@Test
public void putIfAbsent_nullExistingValue() {
  var map = new Object2ObjectOpenHashMap<Object, Object>();
  map.put("a", null);
  map.putIfAbsent("a", "b");
  assertThat(map).containsEntry("a", "b");
}
FAILED: Test.putIfAbsent_nullExistingValue
key is present but with a different value
value of: map.get(a)
expected: b
but was : null
map was : {a=>null}

The computeIfAbsent method has similar wording and fails in this scenario.

I have requested that this peculiarity of the api be added to Guava's testlib.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions