How can I concatenate two arrays in Java?

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

    How about simply

    public static class Array {
    
        public static  T[] concat(T[]... arrays) {
            ArrayList al = new ArrayList();
            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.

提交回复
热议问题