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

2
  • 3
    Have you tried anything. If yes then please show us and let us know where exactly you are encountering problem. Commented Apr 30, 2013 at 0:32
  • This question should be locked as a dupe. See stackoverflow.com/questions/80476/… Commented Apr 30, 2013 at 0:59

4 Answers 4

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);
Sign up to request clarification or add additional context in comments.

Comments

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);

2 Comments

This seems like a needless introduction of an external library for a very small piece of functionality, no?
@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.
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.

1 Comment

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.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.