Merge All array and return one big array - Java Collection Framework

Java examples for Collection Framework:Array Merge

Description

Merge All array and return one big array

Demo Code


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

public class Main {

    @SafeVarargs//from www. jav  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