Java當咱們想要對一個數組進行一些操做,同時又不但願對原來的數組數據有影響的時候,使用引用是不能知足咱們的需求的,
這時候咱們可使用System.arraycopy()方法實現,對用這兩種複製方式,咱們習慣稱前者爲淺複製,後者爲深複製。深複製的
實現方法以下:java
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()); }