Java当我们想要对一个数组进行一些操作,同时又不希望对原来的数组数据有影响的时候,使用引用是不能满足我们的需求的,
这时候我们可以使用System.arraycopy()方法实现,对用这两种复制方式,我们习惯称前者为浅复制,后者为深复制。深复制的
实现方法如下:
public static void arraycopyTest() {
int[] arr = {1,2,3};
int[] array = new int[arr.length];
System.arraycopy(arr,0,array,0,arr.length);
array[1] = 0;
array[2] = 0;
System.out.println(Arrays.toString(arr));
System.out.println(Arrays.toString(array));
}
像上面复制的问题,在集合中我们也刚遇到过,下面以HashMap实现深复制为例,代码如下:
public static void hashMapcopyTest() {
Map srcMap = new HashMap<String,String>();
srcMap.put("1","test1");
srcMap.put("2","test2");
srcMap.put("3","test3");
Map destMap = new HashMap();
destMap.putAll(srcMap);
destMap.remove("1");
destMap.remove("2");
System.out.println(srcMap.toString());
System.out.println(destMap.toString());
}