How can I concatenate two arrays in Java?

后端 未结 30 2090
走了就别回头了
走了就别回头了 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:40

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

提交回复
热议问题