//数组拷贝 public class Test { public static void main(String[] args) { String[] s = {"Microsoft", "IBM", "Sun", "Oracle", "Apple"}; String[] sCopy = new String[6]; System.arraycopy(s, 0, sCopy, 0, s.length); for(int i = 0; i < s.length; i++) { System.out.print(s[i] + " "); } System.out.println(); for(int i = 0; i < sCopy.length; i++) { System.out.print(sCopy[i] + " "); } System.out.println(); int [][] intArray = {{1, 2}, {1, 3, 4}, {4, 9}}; int [][] intArrayCopy = new int [3][]; System.arraycopy(intArray, 0, intArrayCopy, 0,intArray.length); //有趣的问题从这里开始 intArrayCopy[2][1] = 100; for(int i = 0; i < intArray.length; i++) { for(int j = 0; j < intArray[i].length; j++) { System.out.print(intArray[i][j] + " "); } System.out.println(); } //浅层复制问题! } }
-----------------------------------------------------------------第二个版本, 对上面版本的一点点优化-----------------------------------------
public class TestArrayCopy { public static void main(String[] args) { String[] s = { "Microsoft", "IBM", "Sun", "Oracle", "Apple" }; String[] sCopy = new String[6]; System.arraycopy(s, 0, sCopy, 0, s.length); for (int i = 0; i < s.length; i++) { System.out.print(s[i] + " "); } System.out.println(); for (int i = 0; i < sCopy.length; i++) { System.out.print(sCopy[i] + " "); } System.out.println(); int[][] intArray = { { 1, 2 }, { 3, 4, 5 }, { 6, 7 } }; int[][] intArrayCopy = new int[3][]; System.arraycopy(intArray, 0, intArrayCopy, 0, intArray.length); /** * 用arraycopy会带来潜在的,浅层复制的问题! */ intArray[2][1] = 100; for(int i = 0; i < intArray.length;i++) { for(int j = 0; j < intArray[i].length;j ++) { System.out.print(intArray[i][j] + " "); } System.out.println(); } System.out.println(); for(int i = 0; i < intArrayCopy.length;i++) { for(int j = 0; j < intArrayCopy[i].length;j ++) { System.out.print(intArrayCopy[i][j] + " "); } System.out.println(); } } }