ACMNexus / google-collections

Automatically exported from code.google.com/p/google-collections
Apache License 2.0
0 stars 0 forks source link

NullPointerException in Functions.forMap().hashCode() #245

Closed GoogleCodeExporter closed 8 years ago

GoogleCodeExporter commented 8 years ago
com.google.common.collect.BiMap
line 45 and 64

hashCode should never throw a NullPointerException for a well-formed object.
In particular, this method should not throw a NullPointerException:

 private void testHashCode(Object o) {
  o.hashCode(); // never throws NullPointerException
 }

However, this unit test fails by throwing a NullPointerException:

 public void applyTest() {
  Function<Object, Object> f = Functions.forMap(new HashMap<Object,
Object>(), null)
  testHashCode(f);
 }

According to the annotation on line 136:

  Map<K, ? extends V> map, @Nullable V defaultValue) {

ForMapWithDefault allows the field defaultValue to be null.

However, ForMapWithDefault overrides the hashCode() method on line 161
as follows:

return map.hashCode() + defaultValue.hashCode();

defaultValue can be null.

Proposed fix:  add the above test to the test suite, and change the
hashCode method on line 161 to the following:

return map.hashCode() + (defaultValue == null ? 0 : defaultValue.hashCode());

com.google.common.base.Functions
line 161

A patch that adds the unit test is in FunctionsForMapHashcodeTest.patch

A patch for the fix is in FunctionsForMapFix.patch

Original issue reported on code.google.com by mala...@gmail.com on 18 Sep 2009 at 11:02

Attachments:

GoogleCodeExporter commented 8 years ago
Thanks for pointing this bug!

I'll ignore the BiMap text, which looks like a cut-and-paste error.

Original comment by jared.l....@gmail.com on 18 Sep 2009 at 11:21

GoogleCodeExporter commented 8 years ago
Our fix (Objects.hashCode(map, defaultValue)) will be in next RC.

Original comment by kevin...@gmail.com on 21 Sep 2009 at 5:51

GoogleCodeExporter commented 8 years ago

Original comment by kevin...@gmail.com on 21 Sep 2009 at 5:51