add variable length list of array to one array - Java Collection Framework

Java examples for Collection Framework:Array Length

Description

add variable length list of array to one array

Demo Code


//package com.java2s;
import java.lang.reflect.Array;

public class Main {

    @SafeVarargs/*from   w  w  w  . j a  v a  2s .  c  o m*/
    public static <T> T[] addAll(T[]... arrays) {
        if (arrays.length == 1) {
            return arrays[0];
        }

        int length = 0;
        for (T[] array : arrays) {
            if (array == null) {
                continue;
            }
            length += array.length;
        }
        T[] result = newArray(arrays.getClass().getComponentType()
                .getComponentType(), length);

        length = 0;
        for (T[] array : arrays) {
            if (array == null) {
                continue;
            }
            System.arraycopy(array, 0, result, length, array.length);
            length += array.length;
        }
        return result;
    }

    @SuppressWarnings("unchecked")
    public static <T> T[] newArray(Class<?> componentType, int newSize) {
        return (T[]) Array.newInstance(componentType, newSize);
    }
}

Related Tutorials