- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
How to merge two arrays in Java
Problem Description
How to merge two arrays?
Solution
This example shows how to merge two arrays into a single array by the use of list.Addall(array1.asList(array2) method of List class and Arrays.toString () method of Array class.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String args[]) {
String a[] = { "A", "E", "I" };
String b[] = { "O", "U" };
List list = new ArrayList(Arrays.asList(a));
list.addAll(Arrays.asList(b));
Object[] c = list.toArray();
System.out.println(Arrays.toString(c));
}
}
Result
The above code sample will produce the following result.
[A, E, I, O, U]
Another sample example of Arrays Merge.
public class HelloWorld {
public static void main(String[] args) {
int[]a = {1,2,3,4};
int[]b = {4,16,1,2,3,22};
int[]c = new int[a.length+b.length];
int count = 0;
for(int i = 0; i < a.length; i++) {
c[i] = a[i];
count++;
}
for(int j = 0; j < b.length;j++) {
c[count++] = b[j];
}
for(int i = 0;i < c.length;i++) System.out.print(c[i]+" ");
}
}
The above code sample will produce the following result.
1,2,3,4,4,16,1,2,3,22
java_arrays.htm
Advertisements