without System.arraycopy (not available in GWT client for example):
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; }
Solution 8:
The Functional Java library has an array wrapper class that equips arrays with handy methods like concatenation.
import static fj.data.Array.array;
...and then
Array<String> both = array(first).append(array(second));
To get the unwrapped array back out, call
String[] s = both.array();
Solution 9:
ArrayList<String> both = new ArrayList(Arrays.asList(first));
both.addAll(Arrays.asList(second));
both.toArray();
Liked By
Write Answer
In java, how to concatenate two arrays
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Join MindStick Community
You have need login or register for voting of answers or question.
Anonymous User
01-Jul-2015public 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;
}