View RSS Feed

My Java Tips

Implementing Clone Method For HashMap in Java

Rate this Entry
by , 11-08-2011 at 04:25 PM (2699 Views)
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.


Java Code:
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}

Submit "Implementing Clone Method For HashMap in Java" to Facebook Submit "Implementing Clone Method For HashMap in Java" to Digg Submit "Implementing Clone Method For HashMap in Java" to del.icio.us Submit "Implementing Clone Method For HashMap in Java" to StumbleUpon Submit "Implementing Clone Method For HashMap in Java" to Google

Tags: None Add / Edit Tags
Categories
Java SE

Comments