Need to concatenate two String arrays in Java. What is the easiest way to do this?
In java, how to concatenate two arrays Anonymous User 3603 01 Jul 2015 Need to concatenate two String arrays in Java.void f(String[] first, String[] second) { String[] both = ???}What is the easiest way to do this?
public Foo[] concat(Foo[] a, Foo[] b) {int aLen = a.length;
int bLen = b.length;
Foo[] c= new Foo[aLen+bLen];
System.arraycopy(a, 0, c, 0, aLen);
System.arraycopy(b, 0, c, aLen, bLen);
return c;
}
public <T> T[] concatenate (T[] a, T[] b) {int aLen = a.length;
int bLen = b.length;
@SuppressWarnings("unchecked")
T[] c = (T[]) Array.newInstance(a.getClass().getComponentType(), aLen+bLen);
System.arraycopy(a, 0, c, 0, aLen);
System.arraycopy(b, 0, c, aLen, bLen);
return c;
}
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;
}
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;
}
String[] f(String[] first, String[] second) {List<String> both = new ArrayList<String>(first.length + second.length);
Collections.addAll(both, first);
Collections.addAll(both, second);
return both.toArray(new String[both.size()]);
}
static String[] concat(String[]... arrays) {int lengh = 0;
for (String[] array : arrays) {
lengh += array.length;
}
String[] result = new String[lengh];
int pos = 0;
for (String[] array : arrays) {
for (String element : array) {
result[pos] = element;
pos++;
}
}
return result;
}