How to Merge Two Arrays in Java
There are following ways to merge two arrays:
- Java arraycopy() method
- Without using arraycopy() method
- Java Collections
Java arraycopy() method
- public static void arraycopy(Object source, int source_position,
- Object destination, int destination_position, int length)
Parameters
- source: It is a source array.
- source_position: Starting point in the source array.
- destination: It is a destination array.
- destination_position: Starting position in the destination array.
- length: The number of array elements to be copied
- import java.util.Arrays;
- public class MergeArrayExample1 {
- public static void main(String[] args) {
- int[] firstArray = {23,45,12,78,4,90,1};
- int[] secondArray = {77,11,45,88,32,56,3};
- int fal = firstArray.length;
- int sal = secondArray.length;
- int[] result = new int[fal+sal];
- System.arraycopy(firstArray, 0, result, 0, fal);
- System.arraycopy(secondArray, 0, result, fal, sal);
- System.out.println(Arrays.toString(result));
- }
- }
Without using arraycopy() method
- public class MergeArrayExample3
- {
- public static void main(String[] args)
- {
- int[] firstArray = {56,78,90,32,67,12};
- int[] secondArray = {11,14,9,5,2,23,15};
- int length = firstArray.length + secondArray.length;
- int[] mergedArray = new int[length];
- int pos = 0;
- for (int element : firstArray)
- {
- mergedArray[pos] = element;
- pos++;
- }
- for (int element : secondArray)
- {
- mergedArray[pos] = element;
- pos++;
- }
- System.out.println(Arrays.toString(mergedArray));
- }
- }
Using Collections
- import java.util.*;
- public class MergeArrayExample4
- {
- public static void main(String args[])
- {
- String str1[] = { "A", "E", "I" };
- String str2[] = { "O", "U" };
- List list = new ArrayList(Arrays.asList(str1));
-
- list.addAll(Arrays.asList(str2));
- Object[] str3 = list.toArray();
- System.out.println(Arrays.toString(str3));
- }
- }
Comments
Post a Comment