多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
# 如何将一个`hashmap`内容复制到另一个`hashmap` > 原文: [https://beginnersbook.com/2014/08/how-to-copy-one-hashmap-content-to-another-hashmap/](https://beginnersbook.com/2014/08/how-to-copy-one-hashmap-content-to-another-hashmap/) 在本教程中,我们将学习如何将一个 HashMap 元素复制到另一个`HashMap`。我们将使用`HashMap`类的`putAll()`方法来执行此操作。完整代码如下: ```java import java.util.HashMap; class HashMapDemo{ public static void main(String[] args) { // Create a HashMap HashMap<Integer, String> hmap = new HashMap<Integer, String>(); //add elements to HashMap hmap.put(1, "AA"); hmap.put(2, "BB"); hmap.put(3, "CC"); hmap.put(4, "DD"); // Create another HashMap HashMap<Integer, String> hmap2 = new HashMap<Integer, String>(); // Adding elements to the recently created HashMap hmap2.put(11, "Hello"); hmap2.put(22, "Hi"); // Copying one HashMap "hmap" to another HashMap "hmap2" hmap2.putAll(hmap); // Displaying HashMap "hmap2" content System.out.println("HashMap 2 contains: "+ hmap2); } } ``` **输出:** ```java HashMap 2 contains: {1=AA, 2=BB, 3=CC, 4=DD, 22=Hi, 11=Hello} ``` `hmap`的所有元素都被复制到`hmap2`。`putAll()`操作不会替换`Map`的现有元素,而是将元素附加到它们。