目录
1.概述
Map是做软件开发中使用频率最高的数据结构之一。它的最大特点是能够快速地进行查找和更改数据,经常被用做缓存以及数据重复检查场景中。很多人在给Map赋值过程中只知道最基础的put方法,下面我将给大家详细介绍下其他赋值方法的区别。
2.内容
2.1 put:【添加】
key不存在,直接添加,put方法返回null;
key存在,新值覆盖旧值,put方法返回旧值。
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
System.out.println("1->"+map.put(1, "a"));
System.out.println("2->"+map.put(2, "b"));
System.out.println("3->"+map.put(2, "c"));
System.out.println("4->"+map);
//控制台输出:
// 1->null
// 2->null
// 3->b
// 4->{1=a, 2=c}
}
2.2 putIfAbsent:【不存在则添加】
key不存在,直接添加,putIfAbsent方法返回null;
key存在,不进行操作,putIfAbsent方法返回旧值。
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
System.out.println("1->"+map.putIfAbsent(1, "a"));
System.out.println("2->"+map.putIfAbsent(2,

最低0.47元/天 解锁文章
1656

被折叠的 条评论
为什么被折叠?



