为什么Java';s的数组复制方法的行为是这样的?
以下代码以各种方式使用Java的数组复制方法:为什么Java';s的数组复制方法的行为是这样的?,java,arrays,Java,Arrays,以下代码以各种方式使用Java的数组复制方法: public static void main(String[] args) { char[] copyFrom={'s','n','a','d','g'}; char[] copyto=new char[7]; System.arraycopy(copyFrom, 1, copyto, 0, 3); System.out.println(new String (copyto)); System.arrayc
public static void main(String[] args) {
char[] copyFrom={'s','n','a','d','g'};
char[] copyto=new char[7];
System.arraycopy(copyFrom, 1, copyto, 0, 3);
System.out.println(new String (copyto));
System.arraycopy(copyFrom, 1, copyto, 1, 3);
System.out.println(new String (copyto));
System.arraycopy(copyFrom, 1, copyto, 2, 3);
System.out.println(new String (copyto));
System.arraycopy(copyFrom, 1, copyto, 4, 3);
System.out.println(new String (copyto));
}
这是输出:
nadnnad
nnnad
尼纳德
为什么
“n”
被重复?因为您使用了一个copyto数组,所以我在注释中向您展示
char[] copyFrom={'s','n','a','d','g'};
char[] copyto=new char[7]; // copyto = {'','','','','','',''}
System.arraycopy(copyFrom, 1, copyto, 0, 3); // copyto = {'n','a','d','','','',''}
System.out.println(new String (copyto));
System.arraycopy(copyFrom, 1, copyto, 1, 3); // copyto = {'n','n','a','d','','',''},
// because first element 'n' stay from previous step
System.out.println(new String (copyto));
System.arraycopy(copyFrom, 1, copyto, 2, 3); // from previous step you have {'n', 'n'} and replace only 2, 3 and 4 elements
// {'n','n','n','a','d','',''},
System.out.println(new String (copyto));
System.arraycopy(copyFrom, 1, copyto, 4, 3); // from previous step you have {'n', 'n', 'n'} and replace only 4, 5 and 6 elements
System.out.println(new String (copyto));
}
您应该每次创建新的copyto阵列:
public static void main(String[] args) {
char[] copyFrom={'s','n','a','d','g'};
char[] copyto=new char[7];
System.arraycopy(copyFrom, 1, copyto, 0, 3);
System.out.println(new String (copyto));
copyto=new char[7];
System.arraycopy(copyFrom, 1, copyto, 1, 3);
System.out.println(new String (copyto));
copyto=new char[7];
System.arraycopy(copyFrom, 1, copyto, 2, 3);
System.out.println(new String (copyto));
copyto=new char[7];
System.arraycopy(copyFrom, 1, copyto, 4, 3);
System.out.println(new String (copyto));
}
因为对
arraycopy
的每次调用都将“nad”复制到目标数组中的不同位置,并且这些目标位置重叠。请参阅。因为您总是从相同的copyFrom索引进行复制,该索引是copyFrom[1]
,但它们是如何重叠的。我正在用不同的行打印它们。。那有可能吗。。??你能解释一下吗我明白了@切斯拉夫