How would I go about adding 2 arrays together?
For example if: array 1= [11,33,4] array 2= [1,5,4]
Then the resultant array should be c=[11,33,4,1,5,4]; Any help would beappreciated
How would I go about adding 2 arrays together?
For example if: array 1= [11,33,4] array 2= [1,5,4]
Then the resultant array should be c=[11,33,4,1,5,4]; Any help would beappreciated
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);
You can do this in Apache Commons Lang. It has a method named addAll. Here's its description:
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.
Here's how you'd use it:
combinedArray = ArrayUtils.addAll(array1, array2);
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.
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