1. 程式人生 > >陣列的複製(Arrays.copyof(),Arrays.copyofRange())

陣列的複製(Arrays.copyof(),Arrays.copyofRange())

int[] s1={1,2,3,4,5,6};
System.out.printf("操作前 (原件)\t%s%n", Arrays.toString(s1));
int s2[] = Arrays.copyOf(s1, 4);//只複製前4個數據
System.out.printf("操作前 (副本)\t%s%n", Arrays.toString(s2));
s2[0] = 10;
s2[1] = 20;
s2[2] = 30;
s2[3] = 40;
System.out.printf("操作後 (原件)\t%s%n", Arrays.toString(s1));//對複製後的陣列的操作不影響源陣列
System.out.printf("操作後 (副本)\t%s%n", Arrays.toString(s2));

int s3[] = Arrays.copyOf(s1, 7);////複製s1全部資料,並增加容量
s3[6]=7;
System.out.printf("操作後 (副本)\t%s%n", Arrays.toString(s3));

int s4[] = Arrays.copyOfRange(s1, 2,10);//根據範圍複製s1資料
System.out.printf("操作後 (副本)\t%s%n", Arrays.toString(s4));