Java's array concatenation is always as simple as in PHP with array_merge method. In Java we need to use System.arraycopy() or org.apache.commons.lang.ArrayUtils.addAll() method. There are the code samples with both of them:
public class ArrayMerge { private int [] firstArray = new int[] {0, 5, 10}; private int [] secondArray = new int[] {11, 15, 16}; private int [] expectedArray = new int[] {0, 5, 10, 11, 15, 16}; @Test public void testArrayCopy() { int[] sourceArray = new int[firstArray.length+secondArray.length]; System.arraycopy(firstArray, 0, sourceArray, 0, firstArray.length); System.arraycopy(secondArray, 0, sourceArray, firstArray.length, secondArray.length); compare(sourceArray); } @Test public void testApacheCommons() { compare(ArrayUtils.addAll(firstArray, secondArray)); } private void compare(int[] sourceArray) { for (int i = 0; i < sourceArray.length; i++) { assertTrue("Generated ("+sourceArray[i]+") value should be the same as expected ("+expectedArray[i]+")", sourceArray[i]==expectedArray[i]); } } }
The test pass well. In the reality, they are no the difference between both of them because Apache's addAll method uses internally System.arraycopy calls as well:
/** * <p>Adds all the elements of the given arrays into a new array.</p> * <p>The new array contains all of the element of {@code array1} followed * by all of the elements {@code array2}. When an array is returned, it is always * a new array.</p> * * <pre> * ArrayUtils.addAll(array1, null) = cloned copy of array1 * ArrayUtils.addAll(null, array2) = cloned copy of array2 * ArrayUtils.addAll([], []) = [] * </pre> * * @param array1 the first array whose elements are added to the new array. * @param array2 the second array whose elements are added to the new array. * @return The new int[] array. * @since 2.1 */ public static int[] addAll(final int[] array1, final int... array2) { if (array1 == null) { return clone(array2); } else if (array2 == null) { return clone(array1); } final int[] joinedArray = new int[array1.length + array2.length]; System.arraycopy(array1, 0, joinedArray, 0, array1.length); System.arraycopy(array2, 0, joinedArray, array1.length, array2.length); return joinedArray; }
System.arraycopy method parameters are, respectively:
- array to copy
- the first position to copy
- source array
- source array first position receiving the copied value
- the quantity of values to copy from one array to another