1

ジェネリックを使用してキーを作成するにはどうすればよいですか? このコードはコンパイルさえしません:

/* populate the map with a new value if the key is not in the map */
private <K,V> boolean autoVivify(Map<K,V> map, K key)
{
  if (! map.containsKey(key))
  {
    map.put(key, new V());
    return false;
  }
  return true;
}
4

3 に答える 3

5

Java-8 では、 を提供してSupplierを使用するのが合理的computeIfAbsentです。

private <K,V> boolean autoVivify(Map<K,V> map, K key, Supplier<V> supplier) {
    boolean[] result = {true};
    map.computeIfAbsent(key, k -> {
      result[0] = false;
      return supplier.get();
    });
    return result[0];
}

使用例:

Map<String, List<String>> map = new HashMap<>();
autoVivify(map, "str", ArrayList::new);

containsKey/putソリューションとは異なり、使用computeIfAbsentは同時マップに対して安全であることに注意してください。競合状態は発生しません。

于 2015-08-26T10:11:57.447 に答える