阅读量:5
putIfAbsent和put都是Java集合框架中Map接口的方法,它们都用于向Map中添加元素。但是,这两个方法之间存在一些关键区别:
-
当键不存在时:
putIfAbsent:如果指定的键不存在于Map中,则将键值对添加到Map中。如果键已经存在,则不会执行任何操作,并返回键对应的旧值(如果存在)。put:将键值对添加到Map中,如果键已经存在,则会覆盖旧的值,并返回键对应的旧值(如果存在)。
-
返回值:
putIfAbsent:返回键对应的旧值(如果存在),否则返回null。put:返回键对应的旧值(如果存在),否则返回null。
下面是一个简单的示例:
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map map = new HashMap<>();
// 使用putIfAbsent
String oldValue1 = map.putIfAbsent("key1", "value1");
System.out.println("Old value for key1 (putIfAbsent): " + oldValue1); // 输出:null
System.out.println("Value for key1 (putIfAbsent): " + map.get("key1")); // 输出:value1
String oldValue2 = map.putIfAbsent("key1", "value2");
System.out.println("Old value for key1 (putIfAbsent): " + oldValue2); // 输出:value1
System.out.println("Value for key1 (putIfAbsent): " + map.get("key1")); // 输出:value1
// 使用put
String oldValue3 = map.put("key2", "value3");
System.out.println("Old value for key2 (put): " + oldValue3); // 输出:null
System.out.println("Value for key2 (put): " + map.get("key2")); // 输出:value3
String oldValue4 = map.put("key1", "value4");
System.out.println("Old value for key1 (put): " + oldValue4); // 输出:value1
System.out.println("Value for key1 (put): " + map.get("key1")); // 输出:value4
}
}
总结:putIfAbsent和put的主要区别在于,当键已经存在于Map中时,putIfAbsent不会修改键对应的值,而put会覆盖旧的值。在其他方面,这两个方法的返回值和行为相似。
以上就是关于“java putifabsent与put区别”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm