Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

putIfAbsent should replace a null value #280

Open
ben-manes opened this issue Oct 16, 2022 · 2 comments
Open

putIfAbsent should replace a null value #280

ben-manes opened this issue Oct 16, 2022 · 2 comments

Comments

@ben-manes
Copy link

ben-manes commented Oct 16, 2022

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.

@vigna
Copy link
Owner

vigna commented Oct 16, 2022

I see, the code is currently shared between primitive types and object types. Probably adding a conditional check for null would solve the problem.

@vigna
Copy link
Owner

vigna commented Oct 16, 2022

(Provided that all that stuff is entirely unnatural and I'm perfectly sure everybody is carefully avoiding relying on those dark corners of the API.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants