java 在java中按值复制数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2371568/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
copying array by value in java
提问by higherDefender
I tried to make an independent copy of an array but couldnt get one. see i cannot copy it integer by integer using a for loop because of efficiency reasons. Is there any other way? This was my code:
我试图制作一个数组的独立副本,但无法获得。由于效率原因,我无法使用 for 循环逐个整数地复制它。有没有其他办法?这是我的代码:
int[] temp = new int[arr.length];
temp = arr;
回答by Chandra Sekar
Look at System.arraycopy()method. Like,
看System.arraycopy()方法。喜欢,
int[] b = new int[a.length];
System.arraycopy(a, 0, b, 0, a.length);
回答by Joachim Sauer
Arrays.copyOf()creates a new copy of an existing array (optionally with a different length).
Arrays.copyOf()创建现有数组的新副本(可选地具有不同的长度)。
回答by Roman
Try using clone ()method for this purpose. As I remember this is the only case where Josh Bloch in Effective Java recommended to use cloning.
尝试clone ()为此目的使用方法。我记得这是有效 Java 中的 Josh Bloch 建议使用克隆的唯一情况。
int[] temp = arr.clone ();
But arrayCopy is much faster. Sample performance test on array of 3,000,000 elements:
但 arrayCopy 快得多。对包含 3,000,000 个元素的数组进行示例性能测试:
System.arrayCopy time: 8ms
arr.clone() time: 29ms
Arrays.copyOf() time: 49ms
simple for-loop time: 75ms
回答by pajton
Check out System.arraycopy(). It can copy arrays of any type and is a preffered(and optimized) way to copy arrays.
查看System.arraycopy()。它可以复制任何类型的数组,并且是复制数组的首选(和优化)方式。
回答by Mnementh
You can use System.arraycopy, but I doubt it will be much more efficient. The memory has to be copied anyways, so the only optimization possible is to copy bigger chunks of memory at once. But the size of a memory chunk copied at once is strongly limited by the processor/system-architecture.
您可以使用System.arraycopy,但我怀疑它会更有效率。无论如何都必须复制内存,因此唯一可能的优化是一次复制更大的内存块。但是一次复制的内存块的大小受到处理器/系统架构的强烈限制。

