How can I concatenate two arrays in Java?

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

    Here's an adaptation of silvertab's solution, with generics retrofitted:

    static  T[] concat(T[] a, T[] b) {
        final int alen = a.length;
        final int blen = b.length;
        final T[] result = (T[]) java.lang.reflect.Array.
                newInstance(a.getClass().getComponentType(), alen + blen);
        System.arraycopy(a, 0, result, 0, alen);
        System.arraycopy(b, 0, result, alen, blen);
        return result;
    }
    

    NOTE: See Joachim's answer for a Java 6 solution. Not only does it eliminate the warning; it's also shorter, more efficient and easier to read!

提交回复
热议问题