I need to concatenate two String
arrays in Java.
void f(String[] first, String[] second) {
String[] both = ???
}
What is the easiest way to do this?
I need to concatenate two String
arrays in Java.
void f(String[] first, String[] second) {
String[] both = ???
}
What is the easiest way to do this?
I've recently fought problems with excessive memory rotation. If a and/or b are known to be commonly empty, here is another adaption of silvertab's code (generified too):
(In either case, array re-usage behaviour shall be clearly JavaDoced!)
Or with the beloved Guava:
Also, there are versions for primitive arrays:
Booleans.concat(first, second)
Bytes.concat(first, second)
Chars.concat(first, second)
Doubles.concat(first, second)
Shorts.concat(first, second)
Ints.concat(first, second)
Longs.concat(first, second)
Floats.concat(first, second)
Wow! lot of complex answers here including some simple ones that depend on external dependencies. how about doing it like this:
I found a one-line solution from the good old Apache Commons Lang library.
ArrayUtils.addAll(T[], T...)
Code:
Here's a simple method that will concatenate two arrays and return the result:
Note that it will not work with primitive data types, only with object types.
The following slightly more complicated version works with both object and primitive arrays. It does this by using
T
instead ofT[]
as the argument type.It also makes it possible to concatenate arrays of two different types by picking the most general type as the component type of the result.
Here is an example: