Generic method to do array Merge - Java Collection Framework

Java examples for Collection Framework:Array Merge

Description

Generic method to do array Merge

Demo Code

/*//from   ww  w . j  a  v  a 2s.  co m
 * oxCore is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
 *
 * Copyright (c) 2014, Gluu
 */
//package com.java2s;
import java.lang.reflect.Array;

public class Main {
    @SuppressWarnings("unchecked")
    public static <T> T[] arrayMerge(T[]... arrays) {
        // Determine required size of new array
        int count = 0;
        for (T[] array : arrays) {
            count += array.length;
        }

        if (count == 0) {
            return (T[]) Array.newInstance(arrays.getClass()
                    .getComponentType().getComponentType(), 0);
        }

        // create new array of required class
        T[] mergedArray = (T[]) Array.newInstance(arrays[0][0].getClass(),
                count);

        // Merge each array into new array
        int start = 0;
        for (T[] array : arrays) {
            System.arraycopy(array, 0, mergedArray, start, array.length);
            start += array.length;
        }

        return (T[]) mergedArray;
    }
}

Related Tutorials