没错,浅表副本不能满足您的要求。它将具有
List原始地图中的副本,但这些副本
List将引用相同的
List对象,因此对
Listfrom
的修改
HashMap将出现在
Listfrom的对应内容中
HashMap。
HashMap在Java中,没有提供深拷贝功能,因此您仍然必须遍历所有条目,
put并在new
条目中进行遍历
HashMap。但是您也应该
List每次都复制一份。像这样:
public static HashMap<Integer, List<MySpecialClass>> copy( HashMap<Integer, List<MySpecialClass>> original){ HashMap<Integer, List<MySpecialClass>> copy = new HashMap<Integer, List<MySpecialClass>>(); for (Map.Entry<Integer, List<MySpecialClass>> entry : original.entrySet()) { copy.put(entry.getKey(),// Or whatever List implementation you'd like here.new ArrayList<MySpecialClass>(entry.getValue())); } return copy;}如果要修改单个
MySpecialClass对象,并且所做的更改未反映在所
List复制的对象中
HashMap,那么您也需要为其创建新副本。



