How can I concatenate two arrays in Java?

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

    Using only Javas own 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).

提交回复
热议问题