如何在Java中按值复制数组?

如何在Java中按值复制数组?,java,arrays,Java,Arrays,可能重复: 我是Java初学者,需要将一个数组的内容复制到另一个变量中。但是,Java总是通过引用而不是通过值传递数组 如果这让人困惑,我的意思是: int test[]={1,2,3,4}; int test2[]; test2=test; test2[2]=8; for(int i=0;i<test2.length;i++) System.out.print(test[i]); // Prints 1284 instead of 1234 基本上我是想把“图像”颠倒过来。代

可能重复:

我是Java初学者,需要将一个数组的内容复制到另一个变量中。但是,Java总是通过引用而不是通过值传递数组

如果这让人困惑,我的意思是:

int test[]={1,2,3,4};
int test2[];
test2=test;
test2[2]=8;
for(int i=0;i<test2.length;i++)
    System.out.print(test[i]); // Prints 1284 instead of 1234

基本上我是想把“图像”颠倒过来。代码中是否有错误?

您需要克隆阵列

test2=test.clone();

从Java 6开始,您可以使用:

对于您希望执行的操作,test.clone()很好。但是如果你想调整大小,copyOf允许你这么做。我认为在性能方面是这样的


如果您需要,将提供更多选项。

因为test和test2都是指向同一数组的指针,所以您可以使用语句
test2[2]=8
来更改
test
test2
的值

解决方案是将test的内容复制到test2中,并更改test2的特定索引处的值

    for (int i=0,i<test.length,i++)
        test2[i]=test[i]
    //Now both arrays have the same values

    test2[2]=8

    for (int j=0,j<test.length,j++)
        System.out.print(test[i])
        System.out.println()
        System.out.print(test2[i])

System.arraycopy:@LuiggiMendoza您可能希望开始使用更新的JavaDocs。肯定有2000个这样的复制品?我很肯定有9000多个。@mΓΓББ好吧,如果你查看评论中的链接,它也指
System.arraycopy
test2 = Arrays.copyOf(test, test.length);
    for (int i=0,i<test.length,i++)
        test2[i]=test[i]
    //Now both arrays have the same values

    test2[2]=8

    for (int j=0,j<test.length,j++)
        System.out.print(test[i])
        System.out.println()
        System.out.print(test2[i])
    1 2 3 4
    1 2 8 4