per*_*eal 1 java generics dictionary autovivification
如何使用泛型创建vivify密钥?这段代码甚至没有编译:
/* 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;
}
Run Code Online (Sandbox Code Playgroud)
在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];
}
Run Code Online (Sandbox Code Playgroud)
用法示例:
Map<String, List<String>> map = new HashMap<>();
autoVivify(map, "str", ArrayList::new);
Run Code Online (Sandbox Code Playgroud)
请注意,与containsKey/put使用的解决方案不同computeIfAbsent,并发映射是安全的:不会发生竞争条件.
| 归档时间: |
|
| 查看次数: |
139 次 |
| 最近记录: |