在 Java 中克隆 HashMap

java 8object oriented programmingprogramming

使用 clone() 方法克隆 HashMap。

以下是我们的 HashMap,元素为 −

HashMap hm1 = new HashMap();
hm1.put("Shirts", new Integer(700));
hm1.put("Trousers", new Integer(600));
hm1.put("Jeans", new Integer(1200));
hm1.put("Android TV", new Integer(450));
hm1.put("Air Purifiers", new Integer(300));
hm1.put("Food Processors", new Integer(950));

创建另一个 HashMap 并将第一个 HashMap 克隆到其中 −

HashMap hm2 = (HashMap)hm1.clone();

以下是在 Java 中克隆 HashMap 的示例 −

示例

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      // Create hash map
      HashMap hm1 = new HashMap();
      hm1.put("Shirts", new Integer(700));
      hm1.put("Trousers", new Integer(600));
      hm1.put("Jeans", new Integer(1200));
      hm1.put("Android TV", new Integer(450));
      hm1.put("Air Purifiers", new Integer(300));
      hm1.put("Food Processors", new Integer(950));
      System.out.println("Map 1 = "+hm1);
      HashMap hm2 = (HashMap)hm1.clone();
      System.out.println("Cloned Map = "+hm2);
   }
}

输出

Map 1 = {Backpack=1200, Belt=600, Wallet=700}
Cloned Map = {Backpack=1200, Belt=600, Wallet=700}

相关文章