beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Clone a HashMap in Java

By Chaitanya Singh | Filed Under: Java.util package

Description

A program to clone a HashMap. We will be using following method of HashMap class to perform cloning.
public Object clone(): Returns a shallow copy of this HashMap instance: the keys and values themselves are not cloned.

Example

import java.util.HashMap;
class HashMapExample{

  public static void main(String args[]) {
 
     // Create a HashMap
     HashMap<Integer, String> hmap = new HashMap<Integer, String>(); 
 
 
     // Adding few elements
     hmap.put(11, "Jack");
     hmap.put(22, "Rock");
     hmap.put(33, "Rick");
     hmap.put(44, "Smith");
     hmap.put(55, "Will");
 
     System.out.println("HashMap contains: "+hmap);
 
     // Creating a new HashMap
     HashMap<Integer, String> hmap2 = new HashMap<Integer, String>(); 
 
     // cloning first HashMap in the second one
     hmap2=(HashMap)hmap.clone();
 
     System.out.println("Cloned Map contains: "+hmap2); 
  } 
}

Output:

HashMap contains: {33=Rick, 55=Will, 22=Rock, 11=Jack, 44=Smith}
Cloned Map contains: {33=Rick, 55=Will, 22=Rock, 11=Jack, 44=Smith}

Enjoyed this post? Try these related posts

  1. Delete all the elements from HashSet
  2. Converting a HashSet to an Array
  3. how to copy one hashmap content to another hashmap
  4. Difference between HashSet and TreeSet
  5. How to convert a HashSet to a TreeSet
  6. Clone a generic LinkedList in Java

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap