有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

为什么Java的数组复制方法会这样?

以下代码以各种方式使用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) 个答案

  1. # 1 楼答案

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