3

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

Steven84
  • 55
  • 1
  • 1
  • 6
  • 3
    Have you tried anything. If yes then please show us and let us know where exactly you are encountering problem. – Smit Apr 30 '13 at 00:32
  • This question should be locked as a dupe. See http://stackoverflow.com/questions/80476/how-to-concatenate-two-arrays-in-java – Gabriel Bauman Apr 30 '13 at 00:59

4 Answers4

7

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);
rolfl
  • 17,539
  • 7
  • 42
  • 76
2

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);
Community
  • 1
  • 1
Daniel Kaplan
  • 62,768
  • 50
  • 234
  • 356
  • This seems like a needless introduction of an external library for a very small piece of functionality, no? – raptortech97 Apr 30 '13 at 00:40
  • 1
    @raptortech97: No. Don't reinvent the wheel. I don't care how simple the wheel is/seems. I've written methods that were one line long but still had a bug in it. `ArrayUtils.addAll` is tested better than a hand-written `System.arraycopy` that accomplishes the same thing. – Daniel Kaplan Apr 30 '13 at 01:19
0

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.

rgettman
  • 176,041
  • 30
  • 275
  • 357
  • That works, but I like my answer better because with Commons Lang you don't have to "be careful". The api doesn't let you make this mistake. – Daniel Kaplan Apr 30 '13 at 00:34
0

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

Jordan.J.D
  • 7,999
  • 11
  • 48
  • 78