我需要在Java中连接两个字符串数组。
void f(String[] first, String[] second) {
String[] both = ???
}
哪种方法最简单?
我需要在Java中连接两个字符串数组。
void f(String[] first, String[] second) {
String[] both = ???
}
哪种方法最简单?
当前回答
看看这个优雅的解决方案(如果您需要除char以外的其他类型,请更改它):
private static void concatArrays(char[] destination, char[]... sources) {
int currPos = 0;
for (char[] source : sources) {
int length = source.length;
System.arraycopy(source, 0, destination, currPos, length);
currPos += length;
}
}
您可以连接每个数组计数。
其他回答
使用高性能System.arraycopy而不需要@SuppressWarnings注释的通用静态版本:
public static <T> T[] arrayConcat(T[] a, T[] b) {
T[] both = Arrays.copyOf(a, a.length + b.length);
System.arraycopy(b, 0, both, a.length, b.length);
return both;
}
我最近一直在与过度的记忆循环作斗争。如果已知a和/或b通常是空的,这里是silvertab代码的另一种修改(也被通用化):
private static <T> T[] concatOrReturnSame(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;
}
编辑:这篇文章的前一个版本指出,像这样的数组重用应该清楚地记录下来。正如Maarten在评论中指出的那样,一般来说,最好删除if语句,这样就不需要文档了。但话说回来,那些if语句首先就是这个特定优化的要点。我会在这里留下这个答案,但要小心!
一个与类型无关的变体(已更新-感谢Volley实例化T):
@SuppressWarnings("unchecked")
public static <T> T[] join(T[]...arrays) {
final List<T> output = new ArrayList<T>();
for(T[] array : arrays) {
output.addAll(Arrays.asList(array));
}
return output.toArray((T[])Array.newInstance(
arrays[0].getClass().getComponentType(), output.size()));
}
使用Java API:
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()]);
}
一种简单但低效的方法(不包括泛型):
ArrayList baseArray = new ArrayList(Arrays.asList(array1));
baseArray.addAll(Arrays.asList(array2));
String concatenated[] = (String []) baseArray.toArray(new String[baseArray.size()]);