如何在Java中连接两个数组?

时间:2022-09-06 15:40:04

I need to concatenate two String arrays in Java.

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

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

What is the easiest way to do this?

最简单的方法是什么?

52 个解决方案

#1


899  

I found a one-line solution from the good old Apache Commons Lang library.
ArrayUtils.addAll(T[], T...)

我从优秀的Apache Commons Lang库中找到了一个单行解决方案。ArrayUtils。addAll(T[],T…)

Code:

代码:

String[] both = (String[])ArrayUtils.addAll(first, second);

#2


709  

Here's a simple method that will concatenate two arrays and return the result:

下面是一个简单的方法,它将连接两个数组并返回结果:

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;
}

Note like it will not work with primitives, only with object types.

请注意,它不会使用原语,只使用对象类型。

The following slightly more complicated version works with both object and primitive arrays. It does this by using T instead of T[] as the argument type.

下面稍微复杂一点的版本与对象和原始数组一起工作。它使用的是T而不是T[]作为参数类型。

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.

它还可以通过选择最一般的类型作为结果的组件类型来连接两种不同类型的数组。

public static <T> T concatenate(T a, T b) {
    if (!a.getClass().isArray() || !b.getClass().isArray()) {
        throw new IllegalArgumentException();
    }

    Class<?> resCompType;
    Class<?> aCompType = a.getClass().getComponentType();
    Class<?> bCompType = b.getClass().getComponentType();

    if (aCompType.isAssignableFrom(bCompType)) {
        resCompType = aCompType;
    } else if (bCompType.isAssignableFrom(aCompType)) {
        resCompType = bCompType;
    } else {
        throw new IllegalArgumentException();
    }

    int aLen = Array.getLength(a);
    int bLen = Array.getLength(b);

    @SuppressWarnings("unchecked")
    T result = (T) Array.newInstance(resCompType, aLen + bLen);
    System.arraycopy(a, 0, result, 0, aLen);
    System.arraycopy(b, 0, result, aLen, bLen);        

    return result;
}

Here is an example:

这是一个例子:

Assert.assertArrayEquals(new int[] { 1, 2, 3 }, concatenate(new int[] { 1, 2 }, new int[] { 3 }));
Assert.assertArrayEquals(new Number[] { 1, 2, 3f }, concatenate(new Integer[] { 1, 2 }, new Number[] { 3f }));

#3


432  

It's possible to write a fully generic version that can even be extended to concatenate any number of arrays. This versions require Java 6, as they use Arrays.copyOf()

可以编写一个完全通用的版本,甚至可以扩展到连接任意数量的数组。这个版本需要Java 6,因为他们使用Arrays.copyOf()

Both versions avoid creating any intermediary List objects and use System.arraycopy() to ensure that copying large arrays is as fast as possible.

这两个版本都避免创建任何中介列表对象和使用System.arraycopy(),以确保尽可能快地复制大型数组。

For two arrays it looks like this:

对于两个数组,它是这样的:

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;
}

And for a arbitrary number of arrays (>= 1) it looks like this:

对于任意数量的数组(>= 1)它看起来是这样的:

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;
}

#4


309  

One-liner in Java 8:

一行程序在Java 8:

String[] both = Stream.concat(Arrays.stream(a), Arrays.stream(b))
                      .toArray(String[]::new);

Or:

或者:

String[] both = Stream.of(a, b).flatMap(Stream::of)
                      .toArray(String[]::new);

#5


164  

Or with the beloved Guava:

或与心爱的番石榴:

String[] both = ObjectArrays.concat(first, second, String.class);

Also, there are versions for primitive arrays:

此外,还有用于原始数组的版本:

  • Booleans.concat(first, second)
  • 布尔值。concat(一、二)
  • Bytes.concat(first, second)
  • 字节。concat(一、二)
  • Chars.concat(first, second)
  • 识字课。concat(一、二)
  • Doubles.concat(first, second)
  • 双打。concat(一、二)
  • Shorts.concat(first, second)
  • 短裤。concat(一、二)
  • Ints.concat(first, second)
  • 整数。concat(一、二)
  • Longs.concat(first, second)
  • 多头。concat(一、二)
  • Floats.concat(first, second)
  • 漂浮。concat(一、二)

#6


53  

Using the Java API:

使用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()]);
}

#7


33  

A solution 100% old java and without System.arraycopy (not available in GWT client for example):

一个100%旧的java和没有系统的解决方案。arraycopy(在GWT客户端不可用):

static String[] concat(String[]... arrays) {
    int length = 0;
    for (String[] array : arrays) {
        length += array.length;
    }
    String[] result = new String[length];
    int pos = 0;
    for (String[] array : arrays) {
        for (String element : array) {
            result[pos] = element;
            pos++;
        }
    }
    return result;
}

#8


29  

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):

我最近一直在努力克服过度记忆的问题。如果a和/或b通常是空的,这里是silvertab代码的另一个调整(generified):

private static <T> T[] concat(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;
}

(In either case, array re-usage behaviour shall be clearly JavaDoced!)

(在这两种情况下,数组重用行为都应该清楚地JavaDoced!)

#9


25  

The Functional Java library has an array wrapper class that equips arrays with handy methods like concatenation.

Functional Java库有一个数组包装器类,它使用类似于连接的简便方法来装备数组。

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();

#10


18  

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

both.toArray(new String[0]);

#11


17  

Here's an adaptation of silvertab's solution, with generics retrofitted:

这是silvertab的解决方案,用仿制药进行改造:

static <T> T[] concat(T[] a, T[] b) {
    final int alen = a.length;
    final int blen = b.length;
    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;
}

NOTE: See Joachim's answer for a Java 6 solution. Not only does it eliminate the warning; it's also shorter, more efficient and easier to read!

注:参见Joachim的Java 6解决方案。它不仅消除了警告;它也更短,更有效率,更容易阅读!

#12


16  

Another way with Java8 using Stream

另一种使用流的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); 
  }

#13


12  

If you use this way so you no need to import any third party class.

如果您使用这种方式,您就无需导入任何第三方类。

If you want concatenate String

如果你想要连接字符串。

Sample code for concate two String Array

对两个字符串数组的示例代码。

public static String[] combineString(String[] first, String[] second){
        int length = first.length + second.length;
        String[] result = new String[length];
        System.arraycopy(first, 0, result, 0, first.length);
        System.arraycopy(second, 0, result, first.length, second.length);
        return result;
    }

If you want concatenate Int

如果你想要连接Int。

Sample code for concate two Integer Array

两个整型数组的样本代码。

public static int[] combineInt(int[] a, int[] b){
        int length = a.length + b.length;
        int[] result = new int[length];
        System.arraycopy(a, 0, result, 0, a.length);
        System.arraycopy(b, 0, result, a.length, b.length);
        return result;
    }

Here is Main method

这是主要方法

    public static void main(String[] args) {

            String [] first = {"a", "b", "c"};
            String [] second = {"d", "e"};

            String [] joined = combineString(first, second);
            System.out.println("concatenated String array : " + Arrays.toString(joined));

            int[] array1 = {101,102,103,104};
            int[] array2 = {105,106,107,108};
            int[] concatenateInt = combineInt(array1, array2);

            System.out.println("concatenated Int array : " + Arrays.toString(concatenateInt));

        }
    }  

We can use this way also.

我们也可以用这种方法。

#14


11  

Please forgive me for adding yet another version to this already long list. I looked at every answer and decided that I really wanted a version with just one parameter in the signature. I also added some argument checking to benefit from early failure with sensible info in case of unexpected input.

请原谅我添加了另一个版本到这个已经很长的列表。我查看了每个答案,并决定我真的想要一个只有一个参数的版本。我还添加了一些参数检查,以便在意外输入的情况下,从早期的失败中获益。

@SuppressWarnings("unchecked")
public static <T> T[] concat(T[]... inputArrays) {
  if(inputArrays.length < 2) {
    throw new IllegalArgumentException("inputArrays must contain at least 2 arrays");
  }

  for(int i = 0; i < inputArrays.length; i++) {
    if(inputArrays[i] == null) {
      throw new IllegalArgumentException("inputArrays[" + i + "] is null");
    }
  }

  int totalLength = 0;

  for(T[] array : inputArrays) {
    totalLength += array.length;
  }

  T[] result = (T[]) Array.newInstance(inputArrays[0].getClass().getComponentType(), totalLength);

  int offset = 0;

  for(T[] array : inputArrays) {
    System.arraycopy(array, 0, result, offset, array.length);

    offset += array.length;
  }

  return result;
}

#15


10  

You could try converting it into a Arraylist and use the addAll method then convert back to an array.

您可以尝试将其转换为Arraylist,并使用addAll方法将其转换回一个数组。

List list = new ArrayList(Arrays.asList(first));
  list.addAll(Arrays.asList(second));
  String[] both = list.toArray();

#16


7  

Here a possible implementation in working code of the pseudo code solution written by silvertab.

这里是silvertab编写的伪代码解决方案的工作代码。

Thanks silvertab!

谢谢silvertab !

public class Array {

   public static <T> T[] concat(T[] a, T[] b, ArrayBuilderI<T> builder) {
      T[] c = builder.build(a.length + b.length);
      System.arraycopy(a, 0, c, 0, a.length);
      System.arraycopy(b, 0, c, a.length, b.length);
      return c;
   }
}

Following next is the builder interface.

接下来是构建器接口。

Note: A builder is necessary because in java it is not possible to do

注意:构建器是必需的,因为在java中是不可能做到的。

new T[size]

新的T(大小)

due to generic type erasure:

由于一般类型的擦除:

public interface ArrayBuilderI<T> {

   public T[] build(int size);
}

Here a concrete builder implementing the interface, building a Integer array:

这里是一个实现接口的具体构建器,构建一个整数数组:

public class IntegerArrayBuilder implements ArrayBuilderI<Integer> {

   @Override
   public Integer[] build(int size) {
      return new Integer[size];
   }
}

And finally the application / test:

最后申请/测试:

@Test
public class ArrayTest {

   public void array_concatenation() {
      Integer a[] = new Integer[]{0,1};
      Integer b[] = new Integer[]{2,3};
      Integer c[] = Array.concat(a, b, new IntegerArrayBuilder());
      assertEquals(4, c.length);
      assertEquals(0, (int)c[0]);
      assertEquals(1, (int)c[1]);
      assertEquals(2, (int)c[2]);
      assertEquals(3, (int)c[3]);
   }
}

#17


6  

Wow! lot of complex answers here including some simple ones that depend on external dependencies. how about doing it like this:

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

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]);

#18


5  

This is a converted function for a String array:

这是一个字符串数组的转换函数:

public String[] mergeArrays(String[] mainArray, String[] addArray) {
    String[] finalArray = new String[mainArray.length + addArray.length];
    System.arraycopy(mainArray, 0, finalArray, 0, mainArray.length);
    System.arraycopy(addArray, 0, finalArray, mainArray.length, addArray.length);

    return finalArray;
}

#19


5  

How about simply

如何简单地

public static class Array {

    public static <T> T[] concat(T[]... arrays) {
        ArrayList<T> al = new ArrayList<T>();
        for (T[] one : arrays)
            Collections.addAll(al, one);
        return (T[]) al.toArray(arrays[0].clone());
    }
}

And just do Array.concat(arr1, arr2). As long as arr1 and arr2 are of the same type, this will give you another array of the same type containing both arrays.

和数组。concat(arr1 arr2)。只要arr1和arr2属于同一类型,这将给您另一个包含两个数组的相同类型的数组。

#20


4  

Here's my slightly improved version of Joachim Sauer's concatAll. It can work on Java 5 or 6, using Java 6's System.arraycopy if it's available at runtime. This method (IMHO) is perfect for Android, as it work on Android <9 (which doesn't have System.arraycopy) but will use the faster method if possible.

这是我稍微改进的Joachim Sauer的concatAll。它可以在Java 5或6上使用Java 6的系统。arraycopy,如果它在运行时可用。这个方法(IMHO)对Android来说是完美的,因为它在Android <9(它没有System.arraycopy)上工作,但是如果可能的话,会使用更快的方法。

  public static <T> T[] concatAll(T[] first, T[]... rest) {
    int totalLength = first.length;
    for (T[] array : rest) {
      totalLength += array.length;
    }
    T[] result;
    try {
      Method arraysCopyOf = Arrays.class.getMethod("copyOf", Object[].class, int.class);
      result = (T[]) arraysCopyOf.invoke(null, first, totalLength);
    } catch (Exception e){
      //Java 6 / Android >= 9 way didn't work, so use the "traditional" approach
      result = (T[]) java.lang.reflect.Array.newInstance(first.getClass().getComponentType(), totalLength);
      System.arraycopy(first, 0, result, 0, first.length);
    }
    int offset = first.length;
    for (T[] array : rest) {
      System.arraycopy(array, 0, result, offset, array.length);
      offset += array.length;
    }
    return result;
  }

#21


4  

Another way to think about the question. To concatenate two or more arrays, one have to do is to list all elements of each arrays, and then build a new array. This sounds like create a List<T> and then calls toArray on it. Some other answers uses ArrayList, and that's fine. But how about implement our own? It is not hard:

另一种思考这个问题的方法。要连接两个或多个数组,需要做的是列出每个数组的所有元素,然后构建一个新的数组。这听起来像是创建一个列表 ,然后调用toArray。一些其他的答案使用ArrayList,这很好。但是如何实现我们自己的呢?它并不难:

private static <T> T[] addAll(final T[] f, final T...o){
    return new AbstractList<T>(){

        @Override
        public T get(int i) {
            return i>=f.length ? o[i - f.length] : f[i];
        }

        @Override
        public int size() {
            return f.length + o.length;
        }

    }.toArray(f);
}

I believe the above is equivalent to solutions that uses System.arraycopy. However I think this one has its own beauty.

我相信上面的内容等价于使用System.arraycopy的解决方案。但是我认为这个有它自己的美。

#22


4  

How about :

如何:

public String[] combineArray (String[] ... strings) {
    List<String> tmpList = new ArrayList<String>();
    for (int i = 0; i < strings.length; i++)
        tmpList.addAll(Arrays.asList(strings[i]));
    return tmpList.toArray(new String[tmpList.size()]);
}

#23


4  

A simple variation allowing the joining of more than one array:

允许加入多个数组的简单变体:

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()]);
}

#24


4  

This works, but you need to insert your own error checking.

这是可行的,但您需要插入自己的错误检查。

public class StringConcatenate {

    public static void main(String[] args){

        // Create two arrays to concatenate and one array to hold both
        String[] arr1 = new String[]{"s","t","r","i","n","g"};
        String[] arr2 = new String[]{"s","t","r","i","n","g"};
        String[] arrBoth = new String[arr1.length+arr2.length];

        // Copy elements from first array into first part of new array
        for(int i = 0; i < arr1.length; i++){
            arrBoth[i] = arr1[i];
        }

        // Copy elements from second array into last part of new array
        for(int j = arr1.length;j < arrBoth.length;j++){
            arrBoth[j] = arr2[j-arr1.length];
        }

        // Print result
        for(int k = 0; k < arrBoth.length; k++){
            System.out.print(arrBoth[k]);
        }

        // Additional line to make your terminal look better at completion!
        System.out.println();
    }
}

It's probably not the most efficient, but it doesn't rely on anything other than Java's own API.

它可能不是最有效的,但它不依赖于Java本身的API。

#25


3  

Using only Javas own API:

仅使用Javas自己的API:


String[] join(String[]... arrays) {
  // calculate size of target array
  int size = 0;
  for (String[] array : arrays) {
    size += array.length;
  }

  // create list of appropriate size
  java.util.List list = new java.util.ArrayList(size);

  // add arrays
  for (String[] array : arrays) {
    list.addAll(java.util.Arrays.asList(array));
  }

  // create and return final array
  return list.toArray(new String[size]);
}

Now, this code ist not the most efficient, but it relies only on standard java classes and is easy to understand. It works for any number of String[] (even zero arrays).

现在,这个代码不是最有效的,但是它只依赖于标准的java类,并且很容易理解。它适用于任意数量的字符串[](即使是零数组)。

#26


3  

An easy, but inefficient, way to do this (generics not included):

一种简单但低效的方法(不包括泛型):

ArrayList baseArray = new ArrayList(Arrays.asList(array1));
baseArray.addAll(Arrays.asList(array2));
String concatenated[] = (String []) baseArray.toArray(new String[baseArray.size()]);

#27


3  

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

#28


3  

A type independent variation (UPDATED - thanks to Volley for instantiating T):

一种独立的变体(更新-感谢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()));
}

#29


2  

If you'd like to work with ArrayLists in the solution, you can try this:

如果您想在解决方案中使用arraylist,您可以尝试以下方法:

public final String [] f(final String [] first, final String [] second) {
    // Assuming non-null for brevity.
    final ArrayList<String> resultList = new ArrayList<String>(Arrays.asList(first));
    resultList.addAll(new ArrayList<String>(Arrays.asList(second)));
    return resultList.toArray(new String [resultList.size()]);
}

#30


2  

public String[] concat(String[]... arrays)
{
    int length = 0;
    for (String[] array : arrays) {
        length += array.length;
    }
    String[] result = new String[length];
    int destPos = 0;
    for (String[] array : arrays) {
        System.arraycopy(array, 0, result, destPos, array.length);
        destPos += array.length;
    }
    return result;
}

#1


899  

I found a one-line solution from the good old Apache Commons Lang library.
ArrayUtils.addAll(T[], T...)

我从优秀的Apache Commons Lang库中找到了一个单行解决方案。ArrayUtils。addAll(T[],T…)

Code:

代码:

String[] both = (String[])ArrayUtils.addAll(first, second);

#2


709  

Here's a simple method that will concatenate two arrays and return the result:

下面是一个简单的方法,它将连接两个数组并返回结果:

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;
}

Note like it will not work with primitives, only with object types.

请注意,它不会使用原语,只使用对象类型。

The following slightly more complicated version works with both object and primitive arrays. It does this by using T instead of T[] as the argument type.

下面稍微复杂一点的版本与对象和原始数组一起工作。它使用的是T而不是T[]作为参数类型。

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.

它还可以通过选择最一般的类型作为结果的组件类型来连接两种不同类型的数组。

public static <T> T concatenate(T a, T b) {
    if (!a.getClass().isArray() || !b.getClass().isArray()) {
        throw new IllegalArgumentException();
    }

    Class<?> resCompType;
    Class<?> aCompType = a.getClass().getComponentType();
    Class<?> bCompType = b.getClass().getComponentType();

    if (aCompType.isAssignableFrom(bCompType)) {
        resCompType = aCompType;
    } else if (bCompType.isAssignableFrom(aCompType)) {
        resCompType = bCompType;
    } else {
        throw new IllegalArgumentException();
    }

    int aLen = Array.getLength(a);
    int bLen = Array.getLength(b);

    @SuppressWarnings("unchecked")
    T result = (T) Array.newInstance(resCompType, aLen + bLen);
    System.arraycopy(a, 0, result, 0, aLen);
    System.arraycopy(b, 0, result, aLen, bLen);        

    return result;
}

Here is an example:

这是一个例子:

Assert.assertArrayEquals(new int[] { 1, 2, 3 }, concatenate(new int[] { 1, 2 }, new int[] { 3 }));
Assert.assertArrayEquals(new Number[] { 1, 2, 3f }, concatenate(new Integer[] { 1, 2 }, new Number[] { 3f }));

#3


432  

It's possible to write a fully generic version that can even be extended to concatenate any number of arrays. This versions require Java 6, as they use Arrays.copyOf()

可以编写一个完全通用的版本,甚至可以扩展到连接任意数量的数组。这个版本需要Java 6,因为他们使用Arrays.copyOf()

Both versions avoid creating any intermediary List objects and use System.arraycopy() to ensure that copying large arrays is as fast as possible.

这两个版本都避免创建任何中介列表对象和使用System.arraycopy(),以确保尽可能快地复制大型数组。

For two arrays it looks like this:

对于两个数组,它是这样的:

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;
}

And for a arbitrary number of arrays (>= 1) it looks like this:

对于任意数量的数组(>= 1)它看起来是这样的:

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;
}

#4


309  

One-liner in Java 8:

一行程序在Java 8:

String[] both = Stream.concat(Arrays.stream(a), Arrays.stream(b))
                      .toArray(String[]::new);

Or:

或者:

String[] both = Stream.of(a, b).flatMap(Stream::of)
                      .toArray(String[]::new);

#5


164  

Or with the beloved Guava:

或与心爱的番石榴:

String[] both = ObjectArrays.concat(first, second, String.class);

Also, there are versions for primitive arrays:

此外,还有用于原始数组的版本:

  • Booleans.concat(first, second)
  • 布尔值。concat(一、二)
  • Bytes.concat(first, second)
  • 字节。concat(一、二)
  • Chars.concat(first, second)
  • 识字课。concat(一、二)
  • Doubles.concat(first, second)
  • 双打。concat(一、二)
  • Shorts.concat(first, second)
  • 短裤。concat(一、二)
  • Ints.concat(first, second)
  • 整数。concat(一、二)
  • Longs.concat(first, second)
  • 多头。concat(一、二)
  • Floats.concat(first, second)
  • 漂浮。concat(一、二)

#6


53  

Using the Java API:

使用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()]);
}

#7


33  

A solution 100% old java and without System.arraycopy (not available in GWT client for example):

一个100%旧的java和没有系统的解决方案。arraycopy(在GWT客户端不可用):

static String[] concat(String[]... arrays) {
    int length = 0;
    for (String[] array : arrays) {
        length += array.length;
    }
    String[] result = new String[length];
    int pos = 0;
    for (String[] array : arrays) {
        for (String element : array) {
            result[pos] = element;
            pos++;
        }
    }
    return result;
}

#8


29  

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):

我最近一直在努力克服过度记忆的问题。如果a和/或b通常是空的,这里是silvertab代码的另一个调整(generified):

private static <T> T[] concat(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;
}

(In either case, array re-usage behaviour shall be clearly JavaDoced!)

(在这两种情况下,数组重用行为都应该清楚地JavaDoced!)

#9


25  

The Functional Java library has an array wrapper class that equips arrays with handy methods like concatenation.

Functional Java库有一个数组包装器类,它使用类似于连接的简便方法来装备数组。

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();

#10


18  

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

both.toArray(new String[0]);

#11


17  

Here's an adaptation of silvertab's solution, with generics retrofitted:

这是silvertab的解决方案,用仿制药进行改造:

static <T> T[] concat(T[] a, T[] b) {
    final int alen = a.length;
    final int blen = b.length;
    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;
}

NOTE: See Joachim's answer for a Java 6 solution. Not only does it eliminate the warning; it's also shorter, more efficient and easier to read!

注:参见Joachim的Java 6解决方案。它不仅消除了警告;它也更短,更有效率,更容易阅读!

#12


16  

Another way with Java8 using Stream

另一种使用流的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); 
  }

#13


12  

If you use this way so you no need to import any third party class.

如果您使用这种方式,您就无需导入任何第三方类。

If you want concatenate String

如果你想要连接字符串。

Sample code for concate two String Array

对两个字符串数组的示例代码。

public static String[] combineString(String[] first, String[] second){
        int length = first.length + second.length;
        String[] result = new String[length];
        System.arraycopy(first, 0, result, 0, first.length);
        System.arraycopy(second, 0, result, first.length, second.length);
        return result;
    }

If you want concatenate Int

如果你想要连接Int。

Sample code for concate two Integer Array

两个整型数组的样本代码。

public static int[] combineInt(int[] a, int[] b){
        int length = a.length + b.length;
        int[] result = new int[length];
        System.arraycopy(a, 0, result, 0, a.length);
        System.arraycopy(b, 0, result, a.length, b.length);
        return result;
    }

Here is Main method

这是主要方法

    public static void main(String[] args) {

            String [] first = {"a", "b", "c"};
            String [] second = {"d", "e"};

            String [] joined = combineString(first, second);
            System.out.println("concatenated String array : " + Arrays.toString(joined));

            int[] array1 = {101,102,103,104};
            int[] array2 = {105,106,107,108};
            int[] concatenateInt = combineInt(array1, array2);

            System.out.println("concatenated Int array : " + Arrays.toString(concatenateInt));

        }
    }  

We can use this way also.

我们也可以用这种方法。

#14


11  

Please forgive me for adding yet another version to this already long list. I looked at every answer and decided that I really wanted a version with just one parameter in the signature. I also added some argument checking to benefit from early failure with sensible info in case of unexpected input.

请原谅我添加了另一个版本到这个已经很长的列表。我查看了每个答案,并决定我真的想要一个只有一个参数的版本。我还添加了一些参数检查,以便在意外输入的情况下,从早期的失败中获益。

@SuppressWarnings("unchecked")
public static <T> T[] concat(T[]... inputArrays) {
  if(inputArrays.length < 2) {
    throw new IllegalArgumentException("inputArrays must contain at least 2 arrays");
  }

  for(int i = 0; i < inputArrays.length; i++) {
    if(inputArrays[i] == null) {
      throw new IllegalArgumentException("inputArrays[" + i + "] is null");
    }
  }

  int totalLength = 0;

  for(T[] array : inputArrays) {
    totalLength += array.length;
  }

  T[] result = (T[]) Array.newInstance(inputArrays[0].getClass().getComponentType(), totalLength);

  int offset = 0;

  for(T[] array : inputArrays) {
    System.arraycopy(array, 0, result, offset, array.length);

    offset += array.length;
  }

  return result;
}

#15


10  

You could try converting it into a Arraylist and use the addAll method then convert back to an array.

您可以尝试将其转换为Arraylist,并使用addAll方法将其转换回一个数组。

List list = new ArrayList(Arrays.asList(first));
  list.addAll(Arrays.asList(second));
  String[] both = list.toArray();

#16


7  

Here a possible implementation in working code of the pseudo code solution written by silvertab.

这里是silvertab编写的伪代码解决方案的工作代码。

Thanks silvertab!

谢谢silvertab !

public class Array {

   public static <T> T[] concat(T[] a, T[] b, ArrayBuilderI<T> builder) {
      T[] c = builder.build(a.length + b.length);
      System.arraycopy(a, 0, c, 0, a.length);
      System.arraycopy(b, 0, c, a.length, b.length);
      return c;
   }
}

Following next is the builder interface.

接下来是构建器接口。

Note: A builder is necessary because in java it is not possible to do

注意:构建器是必需的,因为在java中是不可能做到的。

new T[size]

新的T(大小)

due to generic type erasure:

由于一般类型的擦除:

public interface ArrayBuilderI<T> {

   public T[] build(int size);
}

Here a concrete builder implementing the interface, building a Integer array:

这里是一个实现接口的具体构建器,构建一个整数数组:

public class IntegerArrayBuilder implements ArrayBuilderI<Integer> {

   @Override
   public Integer[] build(int size) {
      return new Integer[size];
   }
}

And finally the application / test:

最后申请/测试:

@Test
public class ArrayTest {

   public void array_concatenation() {
      Integer a[] = new Integer[]{0,1};
      Integer b[] = new Integer[]{2,3};
      Integer c[] = Array.concat(a, b, new IntegerArrayBuilder());
      assertEquals(4, c.length);
      assertEquals(0, (int)c[0]);
      assertEquals(1, (int)c[1]);
      assertEquals(2, (int)c[2]);
      assertEquals(3, (int)c[3]);
   }
}

#17


6  

Wow! lot of complex answers here including some simple ones that depend on external dependencies. how about doing it like this:

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

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]);

#18


5  

This is a converted function for a String array:

这是一个字符串数组的转换函数:

public String[] mergeArrays(String[] mainArray, String[] addArray) {
    String[] finalArray = new String[mainArray.length + addArray.length];
    System.arraycopy(mainArray, 0, finalArray, 0, mainArray.length);
    System.arraycopy(addArray, 0, finalArray, mainArray.length, addArray.length);

    return finalArray;
}

#19


5  

How about simply

如何简单地

public static class Array {

    public static <T> T[] concat(T[]... arrays) {
        ArrayList<T> al = new ArrayList<T>();
        for (T[] one : arrays)
            Collections.addAll(al, one);
        return (T[]) al.toArray(arrays[0].clone());
    }
}

And just do Array.concat(arr1, arr2). As long as arr1 and arr2 are of the same type, this will give you another array of the same type containing both arrays.

和数组。concat(arr1 arr2)。只要arr1和arr2属于同一类型,这将给您另一个包含两个数组的相同类型的数组。

#20


4  

Here's my slightly improved version of Joachim Sauer's concatAll. It can work on Java 5 or 6, using Java 6's System.arraycopy if it's available at runtime. This method (IMHO) is perfect for Android, as it work on Android <9 (which doesn't have System.arraycopy) but will use the faster method if possible.

这是我稍微改进的Joachim Sauer的concatAll。它可以在Java 5或6上使用Java 6的系统。arraycopy,如果它在运行时可用。这个方法(IMHO)对Android来说是完美的,因为它在Android <9(它没有System.arraycopy)上工作,但是如果可能的话,会使用更快的方法。

  public static <T> T[] concatAll(T[] first, T[]... rest) {
    int totalLength = first.length;
    for (T[] array : rest) {
      totalLength += array.length;
    }
    T[] result;
    try {
      Method arraysCopyOf = Arrays.class.getMethod("copyOf", Object[].class, int.class);
      result = (T[]) arraysCopyOf.invoke(null, first, totalLength);
    } catch (Exception e){
      //Java 6 / Android >= 9 way didn't work, so use the "traditional" approach
      result = (T[]) java.lang.reflect.Array.newInstance(first.getClass().getComponentType(), totalLength);
      System.arraycopy(first, 0, result, 0, first.length);
    }
    int offset = first.length;
    for (T[] array : rest) {
      System.arraycopy(array, 0, result, offset, array.length);
      offset += array.length;
    }
    return result;
  }

#21


4  

Another way to think about the question. To concatenate two or more arrays, one have to do is to list all elements of each arrays, and then build a new array. This sounds like create a List<T> and then calls toArray on it. Some other answers uses ArrayList, and that's fine. But how about implement our own? It is not hard:

另一种思考这个问题的方法。要连接两个或多个数组,需要做的是列出每个数组的所有元素,然后构建一个新的数组。这听起来像是创建一个列表 ,然后调用toArray。一些其他的答案使用ArrayList,这很好。但是如何实现我们自己的呢?它并不难:

private static <T> T[] addAll(final T[] f, final T...o){
    return new AbstractList<T>(){

        @Override
        public T get(int i) {
            return i>=f.length ? o[i - f.length] : f[i];
        }

        @Override
        public int size() {
            return f.length + o.length;
        }

    }.toArray(f);
}

I believe the above is equivalent to solutions that uses System.arraycopy. However I think this one has its own beauty.

我相信上面的内容等价于使用System.arraycopy的解决方案。但是我认为这个有它自己的美。

#22


4  

How about :

如何:

public String[] combineArray (String[] ... strings) {
    List<String> tmpList = new ArrayList<String>();
    for (int i = 0; i < strings.length; i++)
        tmpList.addAll(Arrays.asList(strings[i]));
    return tmpList.toArray(new String[tmpList.size()]);
}

#23


4  

A simple variation allowing the joining of more than one array:

允许加入多个数组的简单变体:

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()]);
}

#24


4  

This works, but you need to insert your own error checking.

这是可行的,但您需要插入自己的错误检查。

public class StringConcatenate {

    public static void main(String[] args){

        // Create two arrays to concatenate and one array to hold both
        String[] arr1 = new String[]{"s","t","r","i","n","g"};
        String[] arr2 = new String[]{"s","t","r","i","n","g"};
        String[] arrBoth = new String[arr1.length+arr2.length];

        // Copy elements from first array into first part of new array
        for(int i = 0; i < arr1.length; i++){
            arrBoth[i] = arr1[i];
        }

        // Copy elements from second array into last part of new array
        for(int j = arr1.length;j < arrBoth.length;j++){
            arrBoth[j] = arr2[j-arr1.length];
        }

        // Print result
        for(int k = 0; k < arrBoth.length; k++){
            System.out.print(arrBoth[k]);
        }

        // Additional line to make your terminal look better at completion!
        System.out.println();
    }
}

It's probably not the most efficient, but it doesn't rely on anything other than Java's own API.

它可能不是最有效的,但它不依赖于Java本身的API。

#25


3  

Using only Javas own API:

仅使用Javas自己的API:


String[] join(String[]... arrays) {
  // calculate size of target array
  int size = 0;
  for (String[] array : arrays) {
    size += array.length;
  }

  // create list of appropriate size
  java.util.List list = new java.util.ArrayList(size);

  // add arrays
  for (String[] array : arrays) {
    list.addAll(java.util.Arrays.asList(array));
  }

  // create and return final array
  return list.toArray(new String[size]);
}

Now, this code ist not the most efficient, but it relies only on standard java classes and is easy to understand. It works for any number of String[] (even zero arrays).

现在,这个代码不是最有效的,但是它只依赖于标准的java类,并且很容易理解。它适用于任意数量的字符串[](即使是零数组)。

#26


3  

An easy, but inefficient, way to do this (generics not included):

一种简单但低效的方法(不包括泛型):

ArrayList baseArray = new ArrayList(Arrays.asList(array1));
baseArray.addAll(Arrays.asList(array2));
String concatenated[] = (String []) baseArray.toArray(new String[baseArray.size()]);

#27


3  

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

#28


3  

A type independent variation (UPDATED - thanks to Volley for instantiating T):

一种独立的变体(更新-感谢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()));
}

#29


2  

If you'd like to work with ArrayLists in the solution, you can try this:

如果您想在解决方案中使用arraylist,您可以尝试以下方法:

public final String [] f(final String [] first, final String [] second) {
    // Assuming non-null for brevity.
    final ArrayList<String> resultList = new ArrayList<String>(Arrays.asList(first));
    resultList.addAll(new ArrayList<String>(Arrays.asList(second)));
    return resultList.toArray(new String [resultList.size()]);
}

#30


2  

public String[] concat(String[]... arrays)
{
    int length = 0;
    for (String[] array : arrays) {
        length += array.length;
    }
    String[] result = new String[length];
    int destPos = 0;
    for (String[] array : arrays) {
        System.arraycopy(array, 0, result, destPos, array.length);
        destPos += array.length;
    }
    return result;
}