Implementing Clone Method For HashMap in Java

28 March 2007

Method “clone”creates and returns a copy of the object. It makes another object of the class in memory. Suppose, We are creating a clone of the object x then x.clone() != x will return true but it is not necessary that x.clone().equals(x) will return true. It depends upon the implementation of class.
Class should implement “Cloneable” interface in order to make clone of its objects. Otherwise “CloneNotSupportedException” will be thrown. Array,HashMap are considered to have implemented the interface “Cloneable”. If by assignment, the contents of the fields of class are not themselves cloned then this method performs shallow copy of this object, not a deep copy operation.
Here I will take example of HashMap class whose “clone” method implements shallow copy not a deep copy as it is not necessary that the contents of all the key/values of Hashmap are themselves cloned. So “clone” method of hashmap performs shallow copy implementation.

import java.util.HashMap;
public class ShallowHashMap {
 
	private HashMap hash;
	public ShallowHashMap(){
		hash = new HashMap() ;
		hash.put ( "one", new Integer ( 1 ) ) ;
		hash.put ( "two", new Integer ( 2 ) ) ;
		hash.put ( "three", new Integer ( 3 ) ) ;
 
	}
 
	private HashMap getHash()
	{
		return hash;
	}
 
	public static void main(String[] args)
	{
 
		ShallowHashMap shallowHashMap = new ShallowHashMap();
		HashMap newHash = ( HashMap )shallowHashMap.getHash().clone ( ) ;
		System.out.println ( "MAP = "+newHash ) ;
	}
 
}Output of the program
 
MAP = {one=1, two=2, three=3}

del.icio.us:Implementing Clone Method For HashMap in Java  digg:Implementing Clone Method For HashMap in Java  spurl:Implementing Clone Method For HashMap in Java  wists:Implementing Clone Method For HashMap in Java  simpy:Implementing Clone Method For HashMap in Java  newsvine:Implementing Clone Method For HashMap in Java  blinklist:Implementing Clone Method For HashMap in Java  furl:Implementing Clone Method For HashMap in Java  reddit:Implementing Clone Method For HashMap in Java  fark:Implementing Clone Method For HashMap in Java  blogmarks:Implementing Clone Method For HashMap in Java  Y!:Implementing Clone Method For HashMap in Java  smarking:Implementing Clone Method For HashMap in Java  magnolia:Implementing Clone Method For HashMap in Java  segnalo:Implementing Clone Method For HashMap in Java  gifttagging:Implementing Clone Method For HashMap in Java

Top Of Page | Trackback

If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.

It will look like this: Implementing Clone Method For HashMap in Java

Leave a Reply