Methods to merge (merge, concat) arrays in Java
public static <T> T[] concat(final T[] array1, final T... array2) {
final Class<?> type1 = array1.getClass().getComponentType();
final T[] joinedArray = (T[]) Array.newInstance(type1, array1.length + array2.length);
System.arraycopy(array1, 0, joinedArray, 0, array1.length);
System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
return joinedArray;
}
import java.lang.reflect.Array;
import java.util.Arrays;
public class ConcatArray {
public static void main(String[] args) {
String[] str1 = { "a", "b", "c" };
String[] str2 = { "d", "e", "f" };
String[] concatStr = concat(str1, str2);
System.out.println(Arrays.toString(concatStr));
}
@SuppressWarnings("unchecked")
public static <T> T[] concat(final T[] array1, final T... array2) {
final Class<?> type1 = array1.getClass().getComponentType();
final T[] joinedArray = (T[]) Array.newInstance(type1, array1.length + array2.length);
System.arraycopy(array1, 0, joinedArray, 0, array1.length);
System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
return joinedArray;
}
}
result
[a, b, c, d, e, f]
import java.lang.reflect.Array;
import java.util.Arrays;
public class ConcatArray2 {
public static void main(String[] args) {
Integer[] int1 = { 1, 2, 3 };
Integer[] concatInt = concat(int1, 4, 5, 6);
System.out.println(Arrays.toString(concatInt));
}
@SuppressWarnings("unchecked")
public static <T> T[] concat(final T[] array1, final T... array2) {
final Class<?> type1 = array1.getClass().getComponentType();
final T[] joinedArray = (T[]) Array.newInstance(type1, array1.length + array2.length);
System.arraycopy(array1, 0, joinedArray, 0, array1.length);
System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
return joinedArray;
}
}
result
[1, 2, 3, 4, 5, 6]
import java.lang.reflect.Array;
import java.util.Arrays;
public class ConcatArray3 {
public static void main(String[] args) {
class Person {
public String name;
public int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}
Person[] person1 = { new Person("Tom", 10), new Person("Jenny", 15) };
Person[] person2 = { new Person("John", 18), new Person("Jack", 22) };
Person[] concatPerson = concat(person1, person2);
System.out.println(Arrays.toString(concatPerson));
}
@SuppressWarnings("unchecked")
public static <T> T[] concat(final T[] array1, final T... array2) {
final Class<?> type1 = array1.getClass().getComponentType();
final T[] joinedArray = (T[]) Array.newInstance(type1, array1.length + array2.length);
System.arraycopy(array1, 0, joinedArray, 0, array1.length);
System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
return joinedArray;
}
}
result
[Person [name=Tom, age=10], Person [name=Jenny, age=15], Person [name=John, age=18], Person [name=Jack, age=22]]
Recommended Posts