问题描述
public Object clone() { HashMap<K,V> result = null;try { result = (HashMap<K,V>)super.clone();} catch (CloneNotSupportedException e) { // assert false;} result.table = new Entry[table.length]; result.entrySet = null; result.modCount = 0; result.size = 0; result.init(); result.putAllForCreate(this); return result; }新建Entry,把原来Entry中数据放到新的Entry中。新的HashMap与旧的HashMap操作没有关系了,为什么还是shallow?
解决方案
javadoc上说得很清楚呀引用 /** * Returns a shallow copy of this <tt>HashMap</tt> instance: the keys and * values themselves are not cloned. * * @return a shallow copy of this map */
解决方案二:
HashMap hm = new HashMap();HashMap hm1 = new HashMap();hm1.put("A", "AA");hm.put(1, "A");hm.put(2, hm1);Object hmc = hm.clone();hm1.put("A", "AAA");hm1.put("B", "BBB");System.out.println(hm.toString());System.out.println(hmc.toString());hm:{1=A, 2={A=AAA, B=BBB}}hmc:{1=A, 2={A=AAA, B=BBB}}
解决方案三:
因为里边的数据还是同一个,所以还是浅拷贝深拷贝是子子孙孙都要复制