Java基础知识:数组复制。
int[] scores1 = {10,23,18};
int[] scores2 = scores1;
数组是对象,上面的程序片段只是将scores1参考的数组对象,也给scores2参考。如果要做到数组复制,基本做法是另行建立新数组。如下:
int[] scores1 = {10,23,18};
int[] scores2 = new int[scores.length];
for (int i = 0; i < scores1.length; i++) {
scores2[i] = scores1[i];
}
以上代码通过建立一个长度与scores1相同的新数组,再逐一访问scores1每个索引元素,并指定给scores2对应的索引位置。事实上,不用自行使用循环做值的复制,而可以使用System.arraycopy() 方法,这个方法会使用原生方式复制每个索引元素,比自行使用循环来得快:
int[] scores1 = {10,23,18};
int[] scores2 = new int[scores.length];
System.arraycopy(scores1, 0, scores2, 0, scores1.length);
System.arraycopy() 的五个参数分别是来源数组、来源起始索引、目的数组、目的起始索引、复制长度。如果使用JDK6以上,还有个更方便的Arrays.copyOf() 方法,你不用另外建立新数组,Arrays.copyOf会帮你建立、如下:
int[] scores1 = {10,23,18};
int[] scores2 = Arrays.copyOf(scores1, scores1.length);
// 下面代码不会影响scores1参考的数组对象
scores2[0] = 99;
在Java中,数组一旦建立,长度就固定了.
数组复制中还分为浅层复制(Shallow copy) 和深层复制(Deep copy)。无论System.arraycopy() 还是Array.copyOf 都是浅层复制,因为复制过程中只是将源索引参考的对象给目标对象的索引去参考,并没有复制对象,术语上来说是复制参考。下面两段代码片段来解释:
class Clothes {
String color;
char size;
Clothes(String color, char size) {
this.color = color;
this.size = size;
}
}
public class shallowCopy {
pubilc 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对象
c1[0].color = "yellow"
System.out.println(c2[0].color);
}
// 输出结果为yellow。
class Clothes2 {
String color;
char size;
Clothes2(String color, char size) {
this.color = color;
this.size = size;
}
}
public class deepCopy {
pubilc 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 Colthes2(c1[i].color, c1[i].size);
c2[i] = c;
}
}
// 通过c1修改索引0对象
c1[0].color = "yellow"
System.out.println(c2[0].color);
}
// 输出结果为red