大多数同步和并发集合(例如 HashTable、ConcurrentHashMap 等)不允许空值。 null 元素有什么具体问题吗?
最佳答案
Hashtable 有点过时了,所以我不会对其发表评论。至于 ConcurrentHashMap
,API 相对于标准 HashMap
的重要补充之一是一些原子方法,例如 putIfAbsent
。 Javadoc:
Returns the previous value associated with the specified key, or null if there was no mapping for the key
特别是,如果映射允许空键,则该方法使用起来会复杂得多。您需要确保值不会被覆盖的典型模式是:
ConcurrentMap<K,V> map = new ConcurrentHashMap<> ();
V value = map.get(key);
if (value == null) {
value = new V();
V previousValue = map.putIfAbsent(key, value);
if (previousValue != null) { //Here you need to be sure what that means
value = previousValue;
}
}
useValue(value);
另一个例子是如何检查键是否在 HashMap 中(并且需要返回值):
V value = map.get(key);
if (value == null && !map.containsKey(key)) {
}
并发环境中的问题是整个事情不是原子的。
关于java - 同步和并发集合中的空元素问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15731689/