import java.util.concurrent.ConcurrentHashMap;
public class MapExample {
public static void main(String[] args) {
// 创建一个 ConcurrentHashMap 实例
ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();
// 使用 putIfAbsent 方法,只有当指定的键不存在时才会插入键值对
String result1 = map.putIfAbsent("key1", "value1");
System.out.println("putIfAbsent result for key1: " + result1); // 输出 null,因为 key1 之前不存在
// 再次尝试插入相同的键,这次不会插入新的值
String result2 = map.putIfAbsent("key1", "newValue");
System.out.println("putIfAbsent result for key1: " + result2); // 输出 value1,因为 key1 已经存在
// 打印当前的 map
System.out.println("Current map: " + map);
}
}
ConcurrentHashMap 是一个线程安全的哈希表实现,适用于多线程环境。putIfAbsent(key, value) 方法的作用是:如果指定的键在映射中不存在,则将该键和对应的值插入映射中。如果键已经存在,则不会更新该键的值,并返回已有的值。putIfAbsent 时,由于 "key1" 尚未存在于映射中,因此方法会插入 "key1" -> "value1" 并返回 null。putIfAbsent 时,由于 "key1" 已经存在,因此方法不会插入新的值,而是返回已有的值 "value1"。上一篇:java字符串转换成日期
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站