Map接口的putAll()方法如何使用?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Map接口的putAll()方法如何使用?相关的知识,希望对你有一定的参考价值。

该问题本人已解决

import Java.util.HashMap;
public class Map_putAllTest
public static void main(String[] args)
//两个map具有不同的key
HashMap map1=new HashMap();
map1.put("1", "A");
HashMap map2 = new HashMap();
map2.put("2", "B");
map2.put("3", "C");
map1.putAll(map2);
System.out.println(map1);
//两个map具有重复的key
HashMap map3=new HashMap();
map3.put("1", "A");
HashMap map4 = new HashMap();
map4.put("1", "B");
map4.put("3", "C");
map3.putAll(map4);
System.out.println(map3);


/* 输出结果:
* 3=C, 2=B, 1=A
* 3=C, 1=B
* 结论:putAll可以合并两个MAP,只不过如果有相同的key那么用后面的覆盖前面的
* */
复制的,不过写的不错,也直观
参考技术A 棒! 没错,其实看看API文档,就明白追问

恩,是的!

Map.putAll()方法

import Java.util.HashMap;

public class Map_putAllTest {
public static void main(String[] args){
   //两个map具有不同的key
   HashMap map1=new HashMap(); 
   map1.put("1", "A"); 
   HashMap map2 = new HashMap(); 
   map2.put("2", "B"); 
   map2.put("3", "C"); 
   map1.putAll(map2); 
   System.out.println(map1);
   //两个map具有重复的key
   HashMap map3=new HashMap(); 
   map3.put("1", "A"); 
   HashMap map4 = new HashMap(); 
   map4.put("1", "B"); 
   map4.put("3", "C"); 
   map3.putAll(map4); 
   System.out.println(map3);
}
}
/* 输出结果:
* {3=C, 2=B, 1=A}
* {3=C, 1=B}
* 结论:putAll可以合并两个MAP,只不过如果有相同的key那么用后面的覆盖前面的
* */

以上是关于Map接口的putAll()方法如何使用?的主要内容,如果未能解决你的问题,请参考以下文章

Map.putAll()方法

Map(接口)集合

双列集合Map及实现该接口的类的常用方法

如何使putAll原子?

Map.putAll()用法

Java中将一个TreeMap添加到另一个TreeMap中怎么做?