How can I concatenate two arrays in Java?

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

    Another way to think about the question. To concatenate two or more arrays, one have to do is to list all elements of each arrays, and then build a new array. This sounds like create a List and then calls toArray on it. Some other answers uses ArrayList, and that's fine. But how about implement our own? It is not hard:

    private static  T[] addAll(final T[] f, final T...o){
        return new AbstractList(){
    
            @Override
            public T get(int i) {
                return i>=f.length ? o[i - f.length] : f[i];
            }
    
            @Override
            public int size() {
                return f.length + o.length;
            }
    
        }.toArray(f);
    }
    

    I believe the above is equivalent to solutions that uses System.arraycopy. However I think this one has its own beauty.

提交回复
热议问题