我需要在Java中连接两个字符串数组。

void f(String[] first, String[] second) {
    String[] both = ???
}

哪种方法最简单?


当前回答

String [] both = new ArrayList<String>(){{addAll(Arrays.asList(first)); addAll(Arrays.asList(second));}}.toArray(new String[0]);

其他回答

ArrayList<String> both = new ArrayList(Arrays.asList(first));
both.addAll(Arrays.asList(second));

both.toArray(new String[0]);

哇!这里有很多复杂的答案,包括一些依赖于外部依赖的简单答案。这样做怎么样:

String [] arg1 = new String{"a","b","c"};
String [] arg2 = new String{"x","y","z"};

ArrayList<String> temp = new ArrayList<String>();
temp.addAll(Arrays.asList(arg1));
temp.addAll(Arrays.asList(arg2));
String [] concatedArgs = temp.toArray(new String[arg1.length+arg2.length]);

这是算盘常用的密码。

String[] a = {"a", "b", "c"};
String[] b = {"1", "2", "3"};
String[] c = N.concat(a, b); // c = ["a", "b", "c", "1", "2", "3"]

// N.concat(...) is null-safety.
a = null;
c = N.concat(a, b); // c = ["1", "2", "3"]

我有一个简单的方法。您不想浪费时间研究复杂的java函数或库。但返回类型应该是String。

String[] f(String[] first, String[] second) {

    // Variable declaration part
    int len1 = first.length;
    int len2 = second.length;
    int lenNew = len1 + len2;
    String[] both = new String[len1+len2];

    // For loop to fill the array "both"
    for (int i=0 ; i<lenNew ; i++){
        if (i<len1) {
            both[i] = first[i];
        } else {
            both[i] = second[i-len1];
        }
    }

    return both;

}

这么简单。。。

FunctionalJava库有一个数组包装器类,它为数组提供了方便的方法,如串联。

import static fj.data.Array.array;

…然后

Array<String> both = array(first).append(array(second));

要取回展开的数组,请调用

String[] s = both.array();