Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Clone HashMap in Java
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
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}Advertisements