java - What is the previous value mentioned in ConcurrentMap.putIfAbsent() -
concurrentmap
specifies return value of putifabsent()
as:
the previous value associated specified key, or null if there no mapping key. (a null return can indicate map associated null key, if implementation supports null values.)
and gives following code example of this.
if (!map.containskey(key)) return map.put(key, value); else return map.get(key); }
the question how can there ever previous value if map.put(key, value)
invoked when no entry exists in map given key ? seems me return current value or null if no entry given key existed prior call putifabsent()
.
consider following lines:
concurrentmap<string, string> map = new concurrenthashmap<>(); system.out.println(map.putifabsent("key", "value1")); // prints null (no previous value) system.out.println(map.putifabsent("key", "value2")); // prints "value1"
on first call putifabsent
, there no value associated key key
. therefore, putifabsent
return null
documented.
on second call, putifabsent
return previous mapping, value1
, value not updated in map because exists.
while true putifabsent
return current value if there mapping key, notion of "previous value" introduced here consistent definition of map.put
, returns previous value. quoting javadoc:
the previous value associated key, or null if there no mapping key.
Comments
Post a Comment