简体   繁体   中英

How exactly keySet(V mappedValue) in ConcurrentHashMap works?

How is this method used? What is it used for? Normally all collection views (including keySet()) do not allow add and addAll methods - because I cannot add any key without respective value. Sorry, but I do not understand API and how to use this method. Could anyone please give a clear example? Does it mean that if I add myNewKey to such key set, then (myNewKey, mappedValue) key-value binding is added to respective (original) map?

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 (ie, 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

This is not the case here. Adding elements to keySet(V mappedValue) is equivalent to putting in the Map new keys associated with the value mappedValue .

if I add myNewKey to such key set, then (myNewKey, mappedValue) key-value binding is added to respective (original) map?

That's correct.

ConcurrentHashMap<String,String> map = new ConcurrentHashMap<>();
Set<String> keySet = map.keySet("sameValue");
keySet.add("key1");
keySet.add("key2");

will result in the same Map as:

ConcurrentHashMap<String,String> map = new ConcurrentHashMap<>();
map.put("key1","sameValue");
map.put("key2","sameValue");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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