为什么Java的数组复制方法表现如此?

时间:2015-12-10 22:29:31

标签: 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.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));
}

这是输出:

  

NAD
  nnad
  nnnad
  nnnanad

为什么要重复"n"

1 个答案:

答案 0 :(得分:0)

因为您使用了一个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));
}