Clone HashMap in Java

Java 8Object Oriented ProgrammingProgramming

Use the clone() method to clone HashMap.

The following is our HashMap with elements −

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));

Create another HashMap and clone the first HashMap into it −

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

The following is an example to clone HashMap in Java −

Example

 Live Demo

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);
   }
}

Output

Map 1 = {Backpack=1200, Belt=600, Wallet=700}
Cloned Map = {Backpack=1200, Belt=600, Wallet=700}
raja
Published on 16-Jan-2019 07:12:05
Advertisements