Given:
public class Test2 {
public static void main(String[] args) {
int ar1[] = {2, 4, 6, 8};
int ar2[] = {1, 3, 5, 7, 9};
ar2 = ar1;
for (int e2 : ar2) {
System.out.print(" " + e2);
}
}
}
What is the result?
A.
2 4 6 8
B.
2 4 6 8 9
C.
1 3 5 7
D.
1 3 5 7 9
題解
程式第5行,已經將原先ar2所參考到的陣列物件拋棄了,無需再顧慮它。如果這邊是要將原先ar1陣列物件的元素複製給ar2的話,應該要這樣寫:
public class Test2 {
public static void main(String[] args) {
int ar1[] = {2, 4, 6, 8};
int ar2[] = {1, 3, 5, 7, 9};
System.arraycopy(ar1, 0, ar2, 0, ar1.length);
for (int e2 : ar2) {
System.out.print(" " + e2);
}
}
}