Two arrays exist. We can combine them into a third array. We can do this in different ways. Some are more efficient, and others have simpler syntax.
By creating another array, we can copy all elements into a single region of storage. For
-loops can be used to quickly copy these elements.
For
-loop exampleLet us begin with this example. We have two arrays—they can have any number of elements, but in this example they both have 6 elements.
for
-loop we copy the first elements into the merged array. The second for
-loop must use an offset.for
-loop ensures we do not overwrite the elements from the first array.import java.util.Arrays; public class Program { public static void main(String[] args) { int[] array1 = { 1, 2, 3, 4, 5 }; int[] array2 = { 5, 4, 3, 2, 1 }; // Create empty array of required length. int[] merged = new int[array1.length + array2.length]; // Copy first array into new array. for (int i = 0; i < array1.length; i++) { merged[i] = array1[i]; } // Copy second array into new array. // ... Use offset to assign elements. for (int i = 0; i < array2.length; i++) { merged[array1.length + i] = array2[i]; } // Print results. System.out.println(Arrays.toString(array1)); System.out.println(Arrays.toString(array2)); System.out.println(Arrays.toString(merged)); } }[1, 2, 3, 4, 5] [5, 4, 3, 2, 1] [1, 2, 3, 4, 5, 5, 4, 3, 2, 1]
Collections.addAll
This approach is a little simpler. We create an ArrayList
of the required element type. Then we use Collections.addAll
to add both arrays to it.
ArrayList
back into a single array with the toArray
method.toArray
method. This is where our new array will be placed.import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; public class Program { public static void main(String[] args) { // Two string arrays we want to combine. String[] array1 = { "cat", "bird", "fish" }; String[] array2 = { "ant", "bee" }; System.out.println(Arrays.toString(array1)); System.out.println(Arrays.toString(array2)); // Create an ArrayList. // ... Add all string arrays with addAll. ArrayList<String> list = new ArrayList<>(); Collections.addAll(list, array1); Collections.addAll(list, array2); // Display ArrayList contents. System.out.println(list.toString()); // Convert ArrayList to String array. // ... This is the final merged array. String[] merged = new String[list.size()]; list.toArray(merged); System.out.println(Arrays.toString(merged)); } }[cat, bird, fish] [ant, bee] [cat, bird, fish, ant, bee] [cat, bird, fish, ant, bee]
Collections.addAll
With Collections.addAll
, we cannot add int
arrays to an ArrayList
of Integers. For int
arrays, using for
-loops is a better solution.
With for
-loops or an ArrayList
and Collections.addAll
we can combine arrays. For more than two arrays, Collections.addAll
may be simpler—fewer offsets will be needed.