I need to concatenate two String
arrays in Java.
void f(String[] first, String[] second) {
String[] both = ???
}
What is t
It's possible to write a fully generic version that can even be extended to concatenate any number of arrays. This versions require Java 6, as they use Arrays.copyOf()
Both versions avoid creating any intermediary List
objects and use System.arraycopy()
to ensure that copying large arrays is as fast as possible.
For two arrays it looks like this:
public static T[] concat(T[] first, T[] second) {
T[] result = Arrays.copyOf(first, first.length + second.length);
System.arraycopy(second, 0, result, first.length, second.length);
return result;
}
And for a arbitrary number of arrays (>= 1) it looks like this:
public static T[] concatAll(T[] first, T[]... rest) {
int totalLength = first.length;
for (T[] array : rest) {
totalLength += array.length;
}
T[] result = Arrays.copyOf(first, totalLength);
int offset = first.length;
for (T[] array : rest) {
System.arraycopy(array, 0, result, offset, array.length);
offset += array.length;
}
return result;
}