原文: https://beginnersbook.com/2014/08/how-to-copy-one-hashmap-content-to-another-hashmap/

    在本教程中,我们将学习如何将一个 HashMap 元素复制到另一个HashMap。我们将使用HashMap类的putAll()方法来执行此操作。完整代码如下:

    1. import java.util.HashMap;
    2. class HashMapDemo{
    3. public static void main(String[] args) {
    4. // Create a HashMap
    5. HashMap<Integer, String> hmap = new HashMap<Integer, String>();
    6. //add elements to HashMap
    7. hmap.put(1, "AA");
    8. hmap.put(2, "BB");
    9. hmap.put(3, "CC");
    10. hmap.put(4, "DD");
    11. // Create another HashMap
    12. HashMap<Integer, String> hmap2 = new HashMap<Integer, String>();
    13. // Adding elements to the recently created HashMap
    14. hmap2.put(11, "Hello");
    15. hmap2.put(22, "Hi");
    16. // Copying one HashMap "hmap" to another HashMap "hmap2"
    17. hmap2.putAll(hmap);
    18. // Displaying HashMap "hmap2" content
    19. System.out.println("HashMap 2 contains: "+ hmap2);
    20. }
    21. }

    输出:

    1. HashMap 2 contains: {1=AA, 2=BB, 3=CC, 4=DD, 22=Hi, 11=Hello}

    hmap的所有元素都被复制到hmap2putAll()操作不会替换Map的现有元素,而是将元素附加到它们。