2

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

Regards,

F

Farid
  • 1,542
  • 3
  • 18
  • 27

3 Answers3

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] + ", " );
    }
brabec
  • 4,632
  • 8
  • 37
  • 63
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);
Adamski
  • 54,009
  • 15
  • 113
  • 152
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)

npinti
  • 51,780
  • 5
  • 72
  • 96