HashMap对象的深层克隆
1.java.util.HashMap 的 clone 方法是浅层copy,clone出来的对象,仅仅是原来对象的一个引用,并且对克隆出来的对象进行操作是无效的。 下面是个例子: import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * @author hzp * */ public class Test { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub HashMap source = new HashMap(); source.put("key1","value1"); source.put("key2","value2"); for(Iterator keyItr = source.keySet().iterator();keyItr.hasNext();) { Object key = keyItr.next(); System.out.println(key + " : "+source.get(key)); } System.out.println("----------------- 1 ----------------"); Map targetMap = (HashMap)source.clone(); for(Iterator keyItr = targetMap.keySet().iterator();keyItr.hasNext();){ Object key = keyItr.next(); System.out.println(key + " : "+source.get(key)); } System.out.println("---------------- 2 ----------------"); Object temp = targetMap.put("key1","modify"); System.out.println("temp : "+temp); for(Iterator keyItr = source.keySet().iterator();keyItr.hasNext();){ Object key = keyItr.next(); System.out.println(key + " : "+source.get(key)); } } } 输出结果为: key1 : value1 key2 : value2 ----------------- 1 ---------------- key1 : value1 key2 : value2 ---------------- 2 ---------------- temp : value1 key1 : value1 key2 : value2 若想实现深层copy,则需要自己重写clone方法。 如下面的例子: import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * @author hzp * */ public class Test { class customHashMap extends HashMap { public customHashMap() { super(); } public customHashMap(int initialCapacity) { super(initialCapacity); } public Object clone() { Map target = new HashMap(); for (Iterator keyIt = this.keySet().iterator(); keyIt.hasNext();) { Object key = keyIt.next(); target.put(key, this.get(key)); } return target; } } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub customHashMap source = (new Test()).new customHashMap(); source.put("key1", "value1"); source.put("key2", "value2"); for (Iterator keyItr = source.keySet().iterator(); keyItr.hasNext();) { Object key = keyItr.next(); System.out.println(key + " : " + source.get(key)); } System.out.println("----------------- 1 ----------------"); Map target = (Map) source.clone(); target.put("key1", "modify"); System.out.println("----------------- 2 the souce map print----------------"); for (Iterator keyItr = source.keySet().iterator(); keyItr.hasNext();) { Object key = keyItr.next(); System.out.println(key + " : " + source.get(key)); } System.out.println("----------------- 3 the target map print----------------"); for (Iterator keyItr = target.keySet().iterator(); keyItr.hasNext();) { Object key = keyItr.next(); System.out.println(key + " : " + target.get(key)); } } } 输出结果: key1 : value1 key2 : value2 ----------------- 1 ---------------- ----------------- 2 the souce map ---------------- key1 : value1 key2 : value2 ----------------- 3 the target map ---------------- key1 : modify key2 : value2