Java Hashmap clone() Method

hashmap-clone-method

Java Hashmap

Hashmap class is a part of java.util package. In hashmap we can store key and value pairs , only with unique keys.If we try to insert a duplicate key it will replace the old value with new value. Many built-in methods are there in hashmap class which makes it easy to perform operations on them, like insertion , deletion and many more. One of those methods is Java Hashmap clone() Method. 

To know more about Hashmap clone() Method read the complete article.

Java Hashmap clone() Method

The hashmap clone() method is used to make a copy of the hashmap. This method returns a shallow of the hashmap.

A shallow copy means that the data is not copied but a reference to key and values  is copied. Below in this page you can find it’s syntax, return values, parameters with detailed examples.

Syntax :

hashmap.clone();

Return values :

Returns a shallow copy of the hashmap.
Java-Hashmap-clone-method

Hashmap clone() Method Examples

Example :

Run
import java.util.*;

public class Main
{
  public static void main (String[]args)
  {

    // Creating an empty HashMap
    HashMap < String, Integer > hash_map_1 =
      new HashMap < String, Integer > ();


    // Mapping integer values to string keys in a empty hashmap
    hash_map_1.put ("Maths", 80);
    hash_map_1.put ("English", 75);
    hash_map_1.put ("Hindi", 85);
    hash_map_1.put ("Science", 90);

    System.out.println ("Original hashmap : " + hash_map_1);


    //making a clone of the hashmap
    HashMap < String, Integer > clone_hashmap =
      (HashMap < String, Integer >) hash_map_1.clone ();

    System.out.println ("clone hashmap : " + clone_hashmap);


  }
}


Output :

Original hashmap : {Maths=80, English=75, Science=90, Hindi=85}
clone hashmap : {Science=90, Maths=80, English=75, Hindi=85}

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription