原文: https://beginnersbook.com/2014/08/how-to-copy-one-hashmap-content-to-another-hashmap/
在本教程中,我们将学习如何将一个 HashMap 元素复制到另一个HashMap。我们将使用HashMap类的putAll()方法来执行此操作。完整代码如下:
import java.util.HashMap;class HashMapDemo{public static void main(String[] args) {// Create a HashMapHashMap<Integer, String> hmap = new HashMap<Integer, String>();//add elements to HashMaphmap.put(1, "AA");hmap.put(2, "BB");hmap.put(3, "CC");hmap.put(4, "DD");// Create another HashMapHashMap<Integer, String> hmap2 = new HashMap<Integer, String>();// Adding elements to the recently created HashMaphmap2.put(11, "Hello");hmap2.put(22, "Hi");// Copying one HashMap "hmap" to another HashMap "hmap2"hmap2.putAll(hmap);// Displaying HashMap "hmap2" contentSystem.out.println("HashMap 2 contains: "+ hmap2);}}
输出:
HashMap 2 contains: {1=AA, 2=BB, 3=CC, 4=DD, 22=Hi, 11=Hello}
hmap的所有元素都被复制到hmap2。putAll()操作不会替换Map的现有元素,而是将元素附加到它们。
