Skip to content

Testlib: Add test that putIfAbsent replaces a null value  #6217

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 HashMap<Object, Object>();
  map.put("a", null);
  map.putIfAbsent("a", "b");
  assertThat(map).containsEntry("a", "b");
}

I found that multiple custom maps which permit null values do not honor this peculiarity (and similar for computeIfAbsent). For example fastutils' adopted the testlib and Object2ObjectOpenHashMap passes its suite, but it mistakenly does not replace the value as shown above.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions