Overload the HashMap clone()

Yesterday I found that I cannot clone the HashMap rightly through the clone() of HashMap. After cloning, The origin HashMap Object also can be modified by clone HashMap. That's a serious problem in the system.

I take a investigation on it and find the answer.The following is the solution.

Cause: the HashMap's clone is a shallow clone.If you want to get a deep one, must overrite the clone method by yourself.

The following codes is my example.Remember that should take the generic type to code it.

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

/**
 * @author ppju
 * @param <K,V>
 *
 */
public class CloneHashMap<K,V> extends HashMap<K, V>{

	private static final long serialVersionUID = -6550003591342797010L;
	
	public Object clone(){
		HashMap<K,V> cloneMap = new HashMap<K,V>();
		Iterator<Entry<K, V>> it = this.entrySet().iterator();
		while(it.hasNext()){
			Map.Entry<K, V> entry = it.next();
			K key = entry.getKey();
			V value = entry.getValue();
			cloneMap.put(key, value);
		}
		return cloneMap;
	}
	
	

	public static void main(String[] args){
		CloneHashMap<String, String> test = new CloneHashMap<String, String>();
		test.put("1", "-----");
		test.put("2", "-----");
		
		Map<String, String> clone = (Map<String, String>)test.clone();
		clone.put("1", "sjflajsl");
		
		System.out.println(test.toString());
		System.out.println(clone.toString());
                System.out.println(test.toString());
		
	}
	
	
}


Welcome to propose your comments. Thank you.

你可能感兴趣的:(java)