java map深拷贝_java Map深度复制问题

展开全部

这里的pos是基础类型,不是引用类型,不需要拿出来单独复制,浅clone就可e5a48de588b63231313335323631343130323136353331333332613737以了,但是attr这个map需要进行深度复制,因为这个是引用类型,复制后的对象修改该属性依然会影响源对象

clone方法可以简单写为@Override

protected Object clone() throws CloneNotSupportedException {

// TODO Auto-generated method stub

Elem elem = (Elem) super.clone();

Map tempMap = new HashMap();

for (Entry e : this.map.entrySet()) {

/**

* 这里的new String(e.getValue())可以直接用e.getValue()代替,

* 写在这里仅仅是提醒当value是其他对象时需要做下处理,比如一个User对象,如果你直接写成

* tempMap.put(e.getKey(), e.getValue());那么肯定是没什么用的,而要写成

* tempMap.put(e.getKey(), e.getValue().clone());

*/

tempMap.put(e.getKey(), new String(e.getValue()));

}

elem.map = tempMap;

return elem;

}

你可能感兴趣的:(java,map深拷贝)