How can I concatenate two arrays in Java?

后端 未结 30 1969
走了就别回头了
走了就别回头了 2020-11-21 06:05

I need to concatenate two String arrays in Java.

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

What is t

30条回答
  •  走了就别回头了
    2020-11-21 06:44

    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.

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

提交回复
热议问题