我有以下内容:
fruitMap.remove(fruitId, fruitProperties);
Run Code Online (Sandbox Code Playgroud)
fruitMap是:
private Map<FruitId, FruitProperties> fruitMap = new HashMap<FruitId, FruitProperties>();
Run Code Online (Sandbox Code Playgroud)
当我尝试构建我的代码时,我得到一个:
ERROR
The method remove(Object) in the type Map<MyImplementation.FruitId, FruitProperties>
is not applicable for the arguments (Map<MyImplementation.FruitId, FruitProperties>)
Run Code Online (Sandbox Code Playgroud)
有什么问题?
请注意,thiis调用是在我的"FruitImplementation"类中的方法"removeFruit()"内.
来自Javadocs:
对于此映射,默认实现等效于:
if (map.containsKey(key) && Objects.equals(map.get(key), value)) {
map.remove(key);
return true;
} else
return false;
Run Code Online (Sandbox Code Playgroud)
默认实现不保证此方法的同步或原子性属性.提供原子性保证的任何实现都必须覆盖此方法并记录其并发属性.
所以你可以使用那个默认实现.把它放在静态助手方法中也许吧.
但是如果这应该是线程安全的,你可能需要添加一些同步代码(或考虑使用ConcurrentMap,顺便说一下,自Java 5以来已经有了remove方法).
如果当前映射到 ,该remove(key, value)方法将删除该条目。该方法是在Java 1.8中添加的。该接口的 Javadoc 提到了以下默认实现:keyvalueMap
if (map.containsKey(key) && Objects.equals(map.get(key), value)) {
map.put(key, newValue);
return true;
} else
return false;
Run Code Online (Sandbox Code Playgroud)
由于该类Objects仅在 Java 1.7 中添加,因此对于 Java 1.6,您必须自己编写相等测试。因此,如果不需要该方法的返回值,可以替换map.remove(key, value)为:
if (map.containsKey(key) {
Object storedValue = map.get(key);
if (storedValue == null ? value == null : storedValue.equals(value)) {
map.remove(key);
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,这不是线程安全的。如果从多个线程访问映射,则必须添加同步块。
| 归档时间: |
|
| 查看次数: |
694 次 |
| 最近记录: |