Java - 将两个数组相加
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16290399/
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
Java - Adding two arrays together
提问by Steven84
How would I go about adding 2 arrays together?
我将如何将 2 个数组加在一起?
For example if: array 1= [11,33,4] array 2= [1,5,4]
例如如果:数组 1= [11,33,4] 数组 2= [1,5,4]
Then the resultant array should be c=[11,33,4,1,5,4]; Any help would beappreciated
那么结果数组应该是 c=[11,33,4,1,5,4]; 任何帮助,将不胜感激
回答by rolfl
Create a third array, copy the two arrays in to it:
创建第三个数组,将两个数组复制到其中:
int[] result = new int[a.length + b.length];
System.arraycopy(a, 0, result, 0, a.length);
System.arraycopy(b, 0, result, a.length, b.length);
回答by Daniel Kaplan
You can do this in Apache Commons Lang. It has a method named addAll. Here's its description:
您可以在 Apache Commons Lang 中执行此操作。它有一个名为addAll的方法。这是它的描述:
Adds all the elements of the given arrays into a new array.
The new array contains all of the element of array1 followed by all of the elements array2. When an array is returned, it is always a new array.
将给定数组的所有元素添加到一个新数组中。
新数组包含array1 的所有元素,后跟array2 的所有元素。当返回一个数组时,它始终是一个新数组。
Here's how you'd use it:
以下是您如何使用它:
combinedArray = ArrayUtils.addAll(array1, array2);
回答by rgettman
Declare the c
array with a length equal to the sum of the lengths of the two arrays. Then use System.arraycopy
to copy the contents of the original arrays into the new array, being careful to copy them into the destination array at the correct start index.
声明c
长度等于两个数组长度之和的数组。然后用于System.arraycopy
将原始数组的内容复制到新数组中,注意将它们复制到目标数组中正确的起始索引处。
回答by Jordan.J.D
I would use an arraylist since the size is not permanent. Then use a loop to add your array to it.
我会使用一个数组列表,因为它的大小不是永久性的。然后使用循环将您的数组添加到它。
http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html
http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html