Java ConcurrentHashMap putIfAbsent() 方法

2024 年 10 月 21 日 | 1 分钟阅读

如果指定的键尚未与任何值映射,则 ConcurrentHashMap 类的 putIfAbsent() 方法会将指定的键和值映射起来。

语法

参数

key - 要与指定值关联的键

value - 与指定键关联的值

返回值

与键关联的先前值,如果键没有映射,则为 null

Throw

NullPointerException.

示例 1

输出

ConcurrentHashMap values : {vowels=5, digits=9, alfabets=26}
new ConcurrentHashMap after  putIfAbsent : {vowels=5, consonent=21, digits=9, alfabets=26}

示例 2

输出

HashMap values :
 {k1=100, k2=200, k3=300, k4=400}
New HashMap after putIfAbsent :
 {k1=100, k2=200, k3=300, k4=400, k5=300, k6=10}