I need to concatenate two String
arrays in Java.
void f(String[] first, String[] second) {
String[] both = ???
}
What is t
Another way to think about the question. To concatenate two or more arrays, one have to do is to list all elements of each arrays, and then build a new array. This sounds like create a List
and then calls toArray
on it. Some other answers uses ArrayList
, and that's fine. But how about implement our own? It is not hard:
private static T[] addAll(final T[] f, final T...o){
return new AbstractList(){
@Override
public T get(int i) {
return i>=f.length ? o[i - f.length] : f[i];
}
@Override
public int size() {
return f.length + o.length;
}
}.toArray(f);
}
I believe the above is equivalent to solutions that uses System.arraycopy
. However I think this one has its own beauty.