Java 从一个数组复制到另一个数组的最佳方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6537589/
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
Best way to copy from one array to another
提问by hans
When I run the following code, nothing gets copied - what am I doing wrong?
当我运行以下代码时,没有任何内容被复制 - 我做错了什么?
Also, is this the best/most efficient way to copy data from one array to another?
另外,这是将数据从一个数组复制到另一个数组的最佳/最有效的方法吗?
public class A {
public static void main(String args[]) {
int a[] = { 1, 2, 3, 4, 5, 6 };
int b[] = new int[a.length];
for (int i = 0; i < a.length; i++) {
a[i] = b[i];
}
}
}
采纳答案by eldarerathis
I think your assignment is backwards:
我认为你的任务是倒退的:
a[i] = b[i];
a[i] = b[i];
should be:
应该:
b[i] = a[i];
b[i] = a[i];
回答by Ted Hopp
There are lots of solutions:
有很多解决方案:
b = Arrays.copyOf(a, a.length);
Which allocates a new array, copies over the elements of a
, and returns the new array.
它分配一个新数组,复制 的元素a
,并返回新数组。
Or
或者
b = new int[a.length];
System.arraycopy(a, 0, b, 0, b.length);
Which copies the source array content into a destination array that you allocate yourself.
它将源数组内容复制到您自己分配的目标数组中。
Or
或者
b = a.clone();
which works very much like Arrays.copyOf()
. See this thread.
这非常像Arrays.copyOf()
. 看到这个线程。
Or the one you posted, if you reverse the direction of the assignment in the loop.
或者你发布的那个,如果你在循环中反转分配的方向。
回答by Amir Raminfar
Use Arrays.copyOfmy friend.
使用Arrays.copyOf我的朋友。