Tuesday 3 June 2014

HashMap : clone() : Returns a shallow copy of this HashMap instance

Object clone()
Returns a shallow copy of this HashMap instance.

import java.util.*;

class HashMapClone{
  public static void main(String args[]){
    HashMap<Integer, String> myMap1 = new HashMap<> ();
  HashMap<Integer, String> myMap2 = new HashMap<> ();
  
  /* Add data to the myMap1 */
  myMap1.put(1, "First");
  myMap1.put(2, "Second");
  myMap1.put(3, "Third");
  myMap1.put(4, "Fourth");
  
  System.out.println("Data in myMap1 is");
  System.out.println(myMap1);
  
  System.out.println("\nCloning myMap1 to myMap2");
  myMap2 = (HashMap)myMap1.clone();
  System.out.println("\nData in myMap2 is");
  System.out.println(myMap2);
  }
}

Output
Data in myMap1 is
{1=First, 2=Second, 3=Third, 4=Fourth}

Cloning myMap1 to myMap2

Data in myMap2 is
{1=First, 2=Second, 3=Third, 4=Fourth}



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment