How can I concatenate two arrays in Java?

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

    A solution 100% old java and without System.arraycopy (not available in GWT client for example):

    static String[] concat(String[]... arrays) {
        int length = 0;
        for (String[] array : arrays) {
            length += array.length;
        }
        String[] result = new String[length];
        int pos = 0;
        for (String[] array : arrays) {
            for (String element : array) {
                result[pos] = element;
                pos++;
            }
        }
        return result;
    }
    

提交回复
热议问题