import java.util.concurrent.ConcurrentHashMap;
public class PutIfAbsentExample {
public static void main(String[] args) {
// 创建一个 ConcurrentHashMap
ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();
// 添加键值对
map.put("key1", "value1");
// 使用 putIfAbsent 方法
// 如果 key2 不存在,则添加 key2 和 value2
String result1 = map.putIfAbsent("key2", "value2");
System.out.println("Result of putIfAbsent for key2: " + result1); // 输出 null,因为 key2 之前不存在
// 再次尝试添加 key2
String result2 = map.putIfAbsent("key2", "newValue2");
System.out.println("Result of putIfAbsent for key2: " + result2); // 输出 value2,因为 key2 已经存在
// 打印最终的 map
System.out.println("Final map: " + map);
}
}
ConcurrentHashMap
是 Java 中的一个线程安全的哈希表实现。putIfAbsent
方法用于在指定的键不存在时插入键值对。如果该键已经存在,则不会更新其值,并返回现有的值。putIfAbsent
方法时,key2
不存在,因此成功插入并返回 null
。putIfAbsent
方法时,key2
已经存在,因此不会更新其值,并返回现有的值 "value2"
。上一篇:java base64转pdf
下一篇:java tolowercase
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站