Java How to Concatenate two Arrays
Tags: ArrayUtils Array
In this Java tutorial, we learn how to write a Java utility class to concatenate two arrays of objects in Java programming language.
How to concatenate two arrays in Java
At this first step, we create a new Java class named ArrayUtils, and implement a new static method named concat(T[] firstArray, T[] secondArray), this method to concatenate two arrays of generic object type T with the following steps:
- Create a new ArrayList object.
- Use the Collections.addAll(Collection<? super T> c, T… elements) method to add first array and seconds array to the ArrayList object.
- Use the ArrayList.toArray(T[] a) method to convert the ArrayList object to expected array value.
ArrayUtils.java
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ArrayUtils {
/**
* This method to concatenate two arrays
* @param firstArray the first array of T
* @param secondArray the second array of T
* @param <T>
* @return the concatenate result array
*/
public static <T> T[] concat(T[] firstArray, T[] secondArray) {
List<T> result = new ArrayList<>();
Collections.addAll(result, firstArray);
Collections.addAll(result, secondArray);
T[] emptyArray = (T[])Array.newInstance(firstArray.getClass().getComponentType(), 0);
return result.toArray(emptyArray);
}
}
In the following example Java program, we learn how to use the above ArrayUtils.concat(T[] firstArray, T[] secondArray) method in Java program.
ArrayUtilsConcatExample.java
import java.util.Arrays;
public class ArrayUtilsConcatExample {
public static void main(String... args) {
String[] array1 = new String[]{"Java", "Kotlin"};
String[] array2 = new String[]{"Spring", "Spring Boot"};
// Concatenate two Arrays
String[] result = ArrayUtils.concat(array1, array2);
System.out.println("array1: " + Arrays.toString(array1));
System.out.println("array2: " + Arrays.toString(array2));
System.out.println("result: " + Arrays.toString(result));
}
}
array1: [Java, Kotlin]
array2: [Spring, Spring Boot]
result: [Java, Kotlin, Spring, Spring Boot]
Happy Coding 😊
Related Articles
Java Convert Hex String to Byte Array
Java Convert Byte Array to Hex String