Merged all arrays into a single array. - Java Collection Framework

Java examples for Collection Framework:Array Merge

Description

Merged all arrays into a single array.

Demo Code


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

public class Main {
    /**//from  w w  w . jav a  2  s. c o  m
     * Merged all arrays into a single array.
     */
    @SuppressWarnings("unchecked")
    public static <T> T[] merge(final T[]... arrays) {
        // Compute total size
        Class<T> type = null;
        int size = 0;
        for (final T[] array : arrays) {
            size += array.length;
            if (type == null && array.length > 0) {
                type = (Class<T>) array[0].getClass();
            }
        }

        // Copy all arrays
        final T[] merged = (T[]) Array.newInstance(type, size);

        int index = 0;
        for (final T[] array : arrays) {
            System.arraycopy(array, 0, merged, index, array.length);
            index += array.length;
        }

        return merged;
    }
}

Related Tutorials