简体   繁体   English

为什么在 Map 接口中有一个 'remove(key, value)' 方法?

[英]Why is there a 'remove(key, value)' method in the Map interface?

I just found out that Map exposes a method for " [removing] the entry for the specified key only if it is currently mapped to the specified value. ".我刚刚发现Map公开了一种方法,用于“ 仅当指定键当前映射到指定值时才[删除]该条目。 ”。 It is defined as:它被定义为:

default boolean remove(Object key, Object value)

I fail to come up with reasons to include this method in the interface of my own custom maps.我没有想出将此方法包含在我自己的自定义地图界面中的理由。 I'm curious, why would anyone want to do this?我很好奇,为什么会有人想要这样做? Can someone provide an example of an algorithm irreplaceable by the default remove(key) (without the 'value' parameter)?有人可以提供一个默认remove(key)不可替代的算法示例(没有“值”参数)吗?

The Javadoc of that method explains it:该方法的 Javadoc 对其进行了解释:

The default implementation is equivalent to, for this map:对于这个 map,默认实现等效于:

 if (map.containsKey(key) && Objects.equals(map.get(key), value)) { map.remove(key); return true; } else return false;

The default implementation makes no guarantees about synchronization or atomicity properties of this method.默认实现不保证此方法的同步或原子性属性。 Any implementation providing atomicity guarantees must override this method and document its concurrency properties.任何提供原子性保证的实现都必须覆盖此方法并记录其并发属性。

In general, as long as you don't have atomicity guarantees, don't override it and use the default implementation above.一般来说,只要你没有原子性保证,就不要覆盖它并使用上面的默认实现。

This is useful in concurrent programming when multiple threads access the same Map. You would need a ConcurrentHashMap which provides atomicity guarantees for remove(Object, Object) .当多个线程访问同一个 Map 时,这在并发编程中很有用。您需要一个ConcurrentHashMap ,它为remove(Object, Object)提供原子性保证。

For example, smth like that (imagine ConcurrentHashMap<String, String> cache is shared between threads):例如,像那样(假设ConcurrentHashMap<String, String> cache在线程之间共享):

String key = ...;
String value = cache.get(key);
//long lasting operation
cache.remove(key, value);

During that "long lasting operation", another thread might have updated the value assigned to key .在那个“持久操作”期间,另一个线程可能已经更新了分配给key的值。 You only want the key to be removed if it is still assigned to the same value as before.如果密钥仍被分配给与以前相同的值,您只希望删除该密钥。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM