2

What is the best way (elegant/efficient) to copy two arrays into a new one ?

Regards,

F

2
  • you should at least try to search a little bit before posting a question.. Commented Nov 23, 2010 at 10:14
  • why down vote? stackoverflow answers questions that have to deal with programming Commented Nov 23, 2010 at 10:54

3 Answers 3

6

My reputation doesn't allow me to comment on Adamski's answer, but there is an error on this line:

 System.arraycopy(src2, 0, dest, src1.length - 1, src2.length); 

With src1.length - 1 as an argument to destPos, you overwrite the last element copied from the src1 array. In this case you overwrite the element on index 4, which is the 5th element of the array.

This code might be easier to understand:

 int[] array1 = { 1, 2, 3 }; int[] array2 = { 4, 5, 6, 7 }; int[] array3 = new int[ array1.length + array2.length ]; System.arraycopy( array1, 0, array3, 0, array1.length ); System.arraycopy( array2, 0, array3, array1.length, array2.length ); for (int i = 0; i < array3.length; i++) { System.out.print( array3[i] + ", " ); } 
Sign up to request clarification or add additional context in comments.

1 Comment

Noted - I've amended my answer.
0

You can use [System.arraycopy][1] as shown here.

[1]: http://download.oracle.com/javase/1.4.2/docs/api/java/lang/System.html#arraycopy(java.lang.Object, int, java.lang.Object, int, int)

Comments

0

Using System.arraycopy takes advantage of the underlying hardware to perform the array copy as efficiently as possible.

In the context of the question you would need to call System.arraycopy twice; e.g.

int[] dest = new int[10]; int[] src1 = new int[5]; int[] src2 = new int[5]; // Populate source arrays with test data. for (int i=0; i<5; ++i) { src1[i] = i; src2[i] = i + 100; } System.arraycopy(src1, 0, dest, 0, src1.length); System.arraycopy(src2, 0, dest, src1.length, src2.length); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.