How can I concatenate two arrays in Java?

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

    You can append the two arrays in two lines of code.

    String[] both = Arrays.copyOf(first, first.length + second.length);
    System.arraycopy(second, 0, both, first.length, second.length);
    

    This is a fast and efficient solution and will work for primitive types as well as the two methods involved are overloaded.

    You should avoid solutions involving ArrayLists, streams, etc as these will need to allocate temporary memory for no useful purpose.

    You should avoid for loops for large arrays as these are not efficient. The built in methods use block-copy functions that are extremely fast.

提交回复
热议问题