C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
New: We create a new array called "merged." This must have the total number of elements required.
For: In the first for-loop we copy the first elements into the merged array. The second for-loop must use an offset.
Tip: The offset for the second for-loop ensures we do not overwrite the elements from the first array.
Java program that uses for-loops to combine arrays
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));
}
}
Output
[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]
[1, 2, 3, 4, 5, 5, 4, 3, 2, 1]
Finally: We can convert our ArrayList back into a single array with the toArray method.
Note: We must pass an array reference to the toArray method. This is where our new array will be placed.
Java program that uses Collections.addAll to combine arrays
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));
}
}
Output
[cat, bird, fish]
[ant, bee]
[cat, bird, fish, ant, bee]
[cat, bird, fish, ant, bee]