How to merge two String[] into one in Java?
It seems to be a very simple question. But how to write code efficiently and concisely is still worth thinking about. Here are four methods, please refer to selection.
1. apache-commons
This is the easiest way. In apache-commons, there is an ArrayUtils.addAll(Object[], Object[]) method, which allows us to do it in one line:
String[] both = (String[]) ArrayUtils.addAll(first, second);
Others need to call the methods provided in the jdk, and wrap it.
static String[] concat(String[] first, String[] second) {
}
For general purpose, I will use generics when possible, so that not only String[] can be used, but other types of arrays can also be used:
static <T> T[] concat(T[] first, T[] second) {
}
Of course, if your jdk does not support generics, or is not available, you can manually replace T with String.
2. System.arraycopy()
static String[] concat(String[] a, String[] b) {
String[] c= new String[a.length+b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
Use as follows:
String[] both = concat(first, second);
3. Arrays.copyOf()
In java6, there is a method Arrays.copyOf(), which is a generic function. We can use it to write a more general merge method:
public static <T> 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;
}
If you want to merge multiple, you can write:
public static <T> 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;
}
Use as follows:
String[] both = concat(first, second);
String[] more = concat(first, second, third, fourth);
4. Array.newInstance
You can also use Array.newInstance to generate an array:
private static <T> T[] concat(T[] a, T[] b) {
final int alen = a.length;
final int blen = b.length;
if (alen == 0) {
return b;
}
if (blen == 0) {
return a;
}
final T[] result = (T[]) java.lang.reflect.Array.
newInstance(a.getClass().getComponentType(), alen + blen);
System.arraycopy(a, 0, result, 0, alen);
System.arraycopy(b, 0, result, alen, blen);
return result;
}