在Java中复制数组时出现意外结果
我如何获得以下程序的输出123346: 5去哪里在Java中复制数组时出现意外结果,java,Java,我如何获得以下程序的输出123346: 5去哪里 public class TestClass { public static void main(String[] args) { int[] scores = { 1, 2, 3, 4, 5, 6}; System.arraycopy(scores, 2, scores, 3, 2); for(int i : scores) System.out.pr
public class TestClass {
public static void main(String[] args) {
int[] scores = { 1, 2, 3, 4, 5, 6};
System.arraycopy(scores, 2, scores, 3, 2);
for(int i : scores)
System.out.print(i);
}
}
从技术上讲,您也覆盖了5和4。看
源对象和目标对象相同,长度参数为2,而索引不同,因此,每个索引处的两个数字将复制到这些位置
来源编号和位置:
1 2[3 4]5 6
目的地位置:
1 2 3[4 5]6
结果:
1 2 3[3 4]6这不是一段非常有用的代码,但您要做的是将2元素从源数组中从索引2开始复制到从索引3开始的数组中 事实上,您到达时带着: 1,2,3,3,4,6 System.arraycopy将元素从源阵列复制到目标阵列。方法签名为: 阵列复制资源阵列、源索引、目的地阵列、目的地索引、要复制的项数 您要做的是将数组同时指定为源和目标。因此,代码开始将元素从源数组firs参数分数复制到目标数组第三个参数分数。它复制了最后一个方法参数-2的2个元素。它开始从方法中索引2第2个参数处的源数组复制元素到索引3第4个参数处开始的目标数组 想象:
INDEX: 0 1 2 3 4 5
3, 4 <- values that are copied (2 elements from index 2)
source: [1, 2, 3, 4, 5, 6]
4, 5 <- those valuse are overwriten (2 elements from index 3)
destination: [1, 2, 3, 4, 5, 6] <- in your case the same array as source
3, 4 <- values from source copied into destination
result: [1, 2, 3, 3, 4, 6]
这将从源索引2中复制2项。因此{3,4}进入目的位置3。由于源阵列和目标阵列是相同的,所以用4覆盖了5
{3 4} <== items copied
{ 1, 2, 3, 4, 5, 6} <== original
0 1 2 3 4 5 <== indexes
{ 1, 2, 3, 3, 4, 6} <== output, the 4 has overwritten the 5, damn
以下是javadoc中arrayCopy的方法签名: 公共静态无效arraycopyObject src, int srcPos, 对象dest, int destPos, 整数长度 在您的通话中:arrayCopyscores,2,scores,3,2;第二个参数是从何处开始拷贝的源位置,即数组中的2和索引“3” 数组索引:0 1 2 3 4 5 得分123456 类似地,第四个参数是目标位置,即数组中的3和索引“4”: 数组索引:0 1 2 3 4 5 得分123456 最后一个参数是要复制的字符串的长度,即2,因此在位置3复制3和4以给出输出 数组索引0 1 2 3 4 5
得分1 2 3 3 4 6在数组中复制4和5的3和4。实际上,它是从索引2处的源数组复制到索引3.5处的数组。真诚的感谢!:
{3 4} <== items copied
{ 1, 2, 3, 4, 5, 6} <== original
0 1 2 3 4 5 <== indexes
{ 1, 2, 3, 3, 4, 6} <== output, the 4 has overwritten the 5, damn