# 陣列複製

```int[] scores1 = {88, 81, 74, 68, 78, 76, 77, 85, 95, 93}; int[] scores2 = scores1;```

```int[] scores1 = {88, 81, 74, 68, 78, 76, 77, 85, 95, 93}; int[] scores2 = new int[scores1.length]; for(int i = 0; i < scores1.length; i++) {     scores2[i] = scores1[i]; }```

```int[] scores1 = {88, 81, 74, 68, 78, 76, 77, 85, 95, 93}; int[] scores2 = new int[scores1.length]; System.arraycopy(scores1, 0, scores2, 0, scores1.length);```

`System.arraycopy()`的五個參數分別是來源陣列、來源起始索引、目的陣列、目的起始索引、複製長度。如果使用JDK6以上，還有個更方便的`Arrays.copyOf()`方法，你不用另行建立新陣列，`Arrays.copyOf()`會幫你建立。例如：

``````package cc.openhome;

import java.util.Arrays;

public class CopyArray {
public static void main(String[] args) {
int[] scores1 = {88, 81, 74, 68, 78, 76, 77, 85, 95, 93};
int[] scores2 = Arrays.copyOf(scores1, scores1.length);
for(int score : scores2) {
System.out.printf("%3d", score);
}
System.out.println();
scores2[0] = 99;
// 不影響score1參考的陣列物件
for(int score : scores1) {
System.out.printf("%3d", score);
}
}
}
``````

88 81 74 68 78 76 77 85 95 93
88 81 74 68 78 76 77 85 95 93

`int[] scores1 = {88, 81, 74, 68, 78, 76, 77, 85, 95, 93};`
`int[] scores2 = Arrays.copyOf(scores1, scores1.length * 2);`
`for(int score : scores2) {`
`    System.out.printf("%3d", score);`
`}`

`Arrays.copyOf()`的第二個參數，實際上就是指定建立的新陣列長度。上面這個程式片段建立的新陣列是20，執行結果顯示原`scores1`複製過去的88到93的元素，而後顯示10個預設值0。

``````package cc.openhome;

class Clothes {
String color;
char size;
Clothes(String color, char size) {
this.color = color;
this.size = size;
}
}

public class ShallowCopy {
public static void main(String[] args) {
Clothes[] c1 = {new Clothes("red", 'L'), new Clothes("blue", 'M')};
Clothes[] c2 = new Clothes[c1.length];
for(int i = 0; i < c1.length; i++) {
c2[i] = c1[i];
}
c1[0].color = "yellow";
System.out.println(c2[0].color);
}
}
``````

``````package cc.openhome;

class Clothes2 {
String color;
char size;
Clothes2(String color, char size) {
this.color = color;
this.size = size;
}
}

public class DeepCopy {
public static void main(String[] args) {
Clothes2[] c1 = {new Clothes2("red", 'L'), new Clothes2("blue", 'M')};
Clothes2[] c2 = new Clothes2[c1.length];
for(int i = 0; i < c1.length; i++) {
Clothes2 c = new Clothes2(c1[i].color, c1[i].size);
c2[i] = c;
}
c1[0].color = "yellow";
System.out.println(c2[0].color);
}
}
``````