ConcurrentHashMap 中的 keySet(V mappedValue) 究竟是如何工作的?
How exactly keySet(V mappedValue) in ConcurrentHashMap works?
这个方法是怎么用的?这有什么用途?通常所有集合视图(包括 keySet())都不允许使用 add 和 addAll 方法——因为我无法添加没有相应值的任何键。抱歉,我不明白 API 以及如何使用此方法。任何人都可以举一个明确的例子吗?这是否意味着 如果我将 myNewKey 添加到此类键集,则 (myNewKey, mappedValue) 键值绑定将添加到相应的(原始)映射?
public ConcurrentHashMap.KeySetView keySet(V mappedValue)
Returns a Set view of the keys in this map, using the given common
mapped value for any additions (i.e., Collection.add(E) and
Collection.addAll(Collection)). This is of course only appropriate if
it is acceptable to use the same value for all additions from this
view.
Normally all collection views (including keySet()) do not allow add and addAll methods - because I cannot add any key without respective value
这里不是这种情况。将元素添加到 keySet(V mappedValue)
相当于放入与值 mappedValue
.
关联的 Map
个新键
if I add myNewKey to such key set, then (myNewKey, mappedValue) key-value binding is added to respective (original) map?
没错。
ConcurrentHashMap<String,String> map = new ConcurrentHashMap<>();
Set<String> keySet = map.keySet("sameValue");
keySet.add("key1");
keySet.add("key2");
将产生与 Map
相同的结果:
ConcurrentHashMap<String,String> map = new ConcurrentHashMap<>();
map.put("key1","sameValue");
map.put("key2","sameValue");
这个方法是怎么用的?这有什么用途?通常所有集合视图(包括 keySet())都不允许使用 add 和 addAll 方法——因为我无法添加没有相应值的任何键。抱歉,我不明白 API 以及如何使用此方法。任何人都可以举一个明确的例子吗?这是否意味着 如果我将 myNewKey 添加到此类键集,则 (myNewKey, mappedValue) 键值绑定将添加到相应的(原始)映射?
public ConcurrentHashMap.KeySetView keySet(V mappedValue)
Returns a Set view of the keys in this map, using the given common mapped value for any additions (i.e., Collection.add(E) and Collection.addAll(Collection)). This is of course only appropriate if it is acceptable to use the same value for all additions from this view.
Normally all collection views (including keySet()) do not allow add and addAll methods - because I cannot add any key without respective value
这里不是这种情况。将元素添加到 keySet(V mappedValue)
相当于放入与值 mappedValue
.
Map
个新键
if I add myNewKey to such key set, then (myNewKey, mappedValue) key-value binding is added to respective (original) map?
没错。
ConcurrentHashMap<String,String> map = new ConcurrentHashMap<>();
Set<String> keySet = map.keySet("sameValue");
keySet.add("key1");
keySet.add("key2");
将产生与 Map
相同的结果:
ConcurrentHashMap<String,String> map = new ConcurrentHashMap<>();
map.put("key1","sameValue");
map.put("key2","sameValue");