在本教程中,我们将学习如何将一个 HashMap 元素复制到另一个HashMap。我们将使用HashMap类的putAll()方法来执行此操作。完整代码如下:
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); }}
输出:
HashMap 2 contains: {1=AA, 2=BB, 3=CC, 4=DD, 22=Hi, 11=Hello}hmap的所有元素都被复制到hmap2。putAll()操作不会替换Map的现有元素,而是将元素附加到它们。
