In Java, you can concatenate two arrays using several methods. Here are the most common approaches:
1. Using System.arraycopy
(All Java Versions)
This method efficiently copies elements from both arrays into a new array.
public static int[] concatenate(int[] array1, int[] array2) {
int[] result = new int[array1.length + array2.length];
System.arraycopy(array1, 0, result, 0, array1.length);
System.arraycopy(array2, 0, result, array1.length, array2.length);
return result;
}
// Example usage:
int[] array1 = {1, 2, 3};
int[] array2 = {4, 5};
int[] concatenated = concatenate(array1, array2); // [1, 2, 3, 4, 5]
Works for any array type (e.g., String[]
, Object[]
):
public static <T> T[] concatenate(T[] array1, T[] array2) {
T[] result = Arrays.copyOf(array1, array1.length + array2.length);
System.arraycopy(array2, 0, result, array1.length, array2.length);
return result;
}
2. Using Java 8+ Streams
Concatenate arrays using the Stream API for a functional approach.
For primitive arrays (e.g., int[]
):
int[] concatenated = IntStream.concat(
Arrays.stream(array1),
Arrays.stream(array2)
).toArray();
For object arrays (e.g., String[]
):
String[] concatenated = Stream.concat(
Arrays.stream(array1),
Arrays.stream(array2)
).toArray(String[]::new);
3. Using Arrays.copyOf
(Combine with arraycopy
)
Create a new array and copy elements sequentially:
public static int[] concatenate(int[] array1, int[] array2) {
int[] result = Arrays.copyOf(array1, array1.length + array2.length);
System.arraycopy(array2, 0, result, array1.length, array2.length);
return result;
}
4. Using Apache Commons Lang (Third-Party Library)
For simplicity, use ArrayUtils.addAll
from Apache Commons Lang:
import org.apache.commons.lang3.ArrayUtils;
int[] concatenated = ArrayUtils.addAll(array1, array2);
Key Considerations
- Null Handling: Check for
null
arrays before concatenation to avoid errors. - Performance:
System.arraycopy
is the fastest method for large arrays. - Java Version: Use streams for Java 8+; otherwise, stick to
arraycopy
.
Example with Generic Method
public static <T> T[] concatenate(T[] array1, T[] array2) {
T[] result = Arrays.copyOf(array1, array1.length + array2.length);
System.arraycopy(array2, 0, result, array1.length, array2.length);
return result;
}
// Usage:
String[] arr1 = {"a", "b"};
String[] arr2 = {"c", "d"};
String[] combined = concatenate(arr1, arr2); // ["a", "b", "c", "d"]
Choose the method that best fits your use case and Java version!