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

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

哪种方法最简单?


当前回答

在Haskell中,您可以执行类似[a,b,c]++[d,e]的操作来获得[a,b,c,d,e]。这些是连接起来的Haskell列表,但很高兴看到Java中的类似运算符用于数组。你不这么认为吗?这是优雅、简单、通用的,而且实现起来并不那么困难。

如果你愿意,我建议你看看Alexander Hristov在破解OpenJDK编译器方面的工作。他解释了如何修改javac源代码以创建新的运算符。他的示例包括定义一个'**'运算符,其中i**j=Math.pow(i,j)。我们可以用这个例子来实现一个连接两个相同类型数组的运算符。

这样做之后,您就绑定到定制的javac来编译代码,但是任何JVM都可以理解生成的字节码。当然,您可以在源代码级别实现自己的数组连接方法,其他答案中有很多关于如何实现的示例!有这么多有用的运算符可以添加,这一个将是其中之一。

其他回答

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

both.toArray(new String[0]);

每个答案都是复制数据并创建新阵列。这并不是绝对必要的,如果您的阵列相当大,这绝对不是您想要做的。Java创建者已经知道数组拷贝是浪费的,这就是为什么他们提供System.arrayCopy()来在我们必须时在Java之外进行这些拷贝的原因。

与其四处复制数据,不如考虑将其保留在原地,并从中提取数据所在的位置。仅仅因为程序员想组织数据位置而复制数据位置并不总是明智的。

// I have arrayA and arrayB; would like to treat them as concatenated
// but leave my damn bytes where they are!
Object accessElement ( int index ) {
     if ( index < 0 ) throw new ArrayIndexOutOfBoundsException(...);
     // is reading from the head part?
     if ( index < arrayA.length )
          return arrayA[ index ];
     // is reading from the tail part?
     if ( index < ( arrayA.length + arrayB.length ) )
          return arrayB[ index - arrayA.length ];
     throw new ArrayIndexOutOfBoundsException(...); // index too large
}

允许连接多个阵列的简单变体:

public static String[] join(String[]...arrays) {

    final List<String> output = new ArrayList<String>();

    for(String[] array : arrays) {
        output.addAll(Arrays.asList(array));
    }

    return output.toArray(new String[output.size()]);
}

我看到许多带有公共静态T[]concat(T[]a,T[]b){}等签名的通用答案,但据我所知,这些答案只适用于Object数组,而不适用于基元数组。下面的代码既适用于对象数组,也适用于基元数组,使其更通用。。。

public static <T> T concat(T a, T b) {
        //Handles both arrays of Objects and primitives! E.g., int[] out = concat(new int[]{6,7,8}, new int[]{9,10});
        //You get a compile error if argument(s) not same type as output. (int[] in example above)
        //You get a runtime error if output type is not an array, i.e., when you do something like: int out = concat(6,7);
        if (a == null && b == null) return null;
        if (a == null) return b;
        if (b == null) return a;
        final int aLen = Array.getLength(a);
        final int bLen = Array.getLength(b);
        if (aLen == 0) return b;
        if (bLen == 0) return a;
        //From here on we really need to concatenate!

        Class componentType = a.getClass().getComponentType();
        final T result = (T)Array.newInstance(componentType, aLen + bLen);
        System.arraycopy(a, 0, result, 0, aLen);
        System.arraycopy(b, 0, result, aLen, bLen);
        return result;
    }

    public static void main(String[] args) {
        String[] out1 = concat(new String[]{"aap", "monkey"}, new String[]{"rat"});
        int[] out2 = concat(new int[]{6,7,8}, new int[]{9,10});
    }

使用流的Java8的另一种方式

  public String[] concatString(String[] a, String[] b){ 
    Stream<String> streamA = Arrays.stream(a);
    Stream<String> streamB = Arrays.stream(b);
    return Stream.concat(streamA, streamB).toArray(String[]::new); 
  }