HashMap putAll()方法是专门用来复制一个新的Map集合的方法,在Java开发中也是经常要用的,因为我们不可能采用“new_map = old_map”这种形式来复制新的Map集合,因为这样操作会影响到原来的Map集合里面的参数,所以我们可以这样操作:
new_hash_map.putAll(exist_hash_map)
使用示例如下:
import java.util.*; public class Hash_Map_Demo { public static void main(String[] args) { // 创建空的map集合 HashMap<Integer, String> hash_map = new HashMap<Integer, String>(); // 添加数据 hash_map.put(10, "Geeks"); hash_map.put(15, "4"); hash_map.put(20, "Geeks"); hash_map.put(25, "Welcomes"); hash_map.put(30, "You"); // 输出map System.out.println("Initial Mappings are: " + hash_map); // 创建一个新的map集合 HashMap<Integer, String> new_hash_map = new HashMap<Integer, String>(); //将旧的map集合数据复制到新的map集合里面 new_hash_map.putAll(hash_map); // 输出新的map集合 System.out.println("The new map looks like this: " + new_hash_map); } }
输出结果如下:
Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4} The new map looks like this: {25=Welcomes, 10=Geeks, 20=Geeks, 30=You, 15=4}