如何使用泛型创建一个活跃的 key ?此代码甚至无法编译:
/* 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;
}
最佳答案
在 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
的解决方案对于并发映射是安全的:不会发生竞争条件。
关于java - map 的通用 autovivify 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32223392/