阅读量:2
putIfAbsent是Java中的一个方法,用于在映射(Map)中插入一个键值对。如果映射中不存在该键,则插入该键值对;否则,不执行任何操作。这个方法属于java.util.Map接口,并提供了多种实现,如HashMap、TreeMap等。
以下是使用putIfAbsent方法的一些示例:
- 使用
HashMap实现:
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
// 尝试插入一个不存在的键值对
String newValue = "value3";
String existingValue = map.putIfAbsent("key1", newValue);
if (existingValue == null) {
System.out.println("Key1 was not present, and has been inserted with value: " + newValue);
} else {
System.out.println("Key1 was already present with value: " + existingValue);
}
}
}
- 使用
TreeMap实现:
import java.util.Map;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
Map map = new TreeMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
// 尝试插入一个不存在的键值对
String newValue = "value3";
String existingValue = map.putIfAbsent("key1", newValue);
if (existingValue == null) {
System.out.println("Key1 was not present, and has been inserted with value: " + newValue);
} else {
System.out.println("Key1 was already present with value: " + existingValue);
}
}
}
在这两个示例中,我们首先创建了一个映射(HashMap或TreeMap),然后尝试插入一个不存在的键值对。putIfAbsent方法返回映射中已存在的键对应的值(如果存在),否则返回null。根据返回值,我们可以判断键是否已经存在于映射中。
以上就是关于“java putifabsent怎样实现”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm