Search code examples
guava

Why Guava StandardTable put method refuse null value


Guava StandardTable class override AbstractTable's put method

// in AbstractTable class
@CanIgnoreReturnValue
@Override
public V put(R rowKey, C columnKey, V value) {
  return row(rowKey).put(columnKey, value);
}

// in StandardTable class
@CanIgnoreReturnValue
@Override
public V put(R rowKey, C columnKey, V value) {
  checkNotNull(rowKey);
  checkNotNull(columnKey);
  checkNotNull(value);
  return getOrCreate(rowKey).put(columnKey, value);
}

i create table use

Tables.newCustomTable(Maps.newLinkedHashMap(), Maps::newHashMap);

my code will set null value into table in some case, but gauva will throw exception in put method, puzzled how can i implement a standard table with nullable value? (i tried to implement ForwardingTable, override get/put method, use specific class replace null value, but it's not enough, for example: row method will return map contains specific class instead of null)


Solution

  • null in general seen as key or value in any Collection or Map is seen as a bad decision. The jdk itself has some examples, ConcurrentHashMap does not allow null keys or values, so does ConcurrentSkipListMap and many others.

    So does static factory methods added in java-9, like Map::of. Even HashMap that does allow a null key and value, so these would both not fail:

    HashMap<String, String> map = new HashMap<>();
    map.put("", null);
    map.put(null, "");
    

    Using any of the new java-8 method of a HashMap will throw a NullPointerException:

     // value trying to be null
     chm.merge("", null, (k, v) -> k);
    

    And the last point is that all guava Collections are not null-tolerant, which to me is great decision.