This method allows to merge 2 arrays - Java Collection Framework

Java examples for Collection Framework:Array Merge

Description

This method allows to merge 2 arrays

Demo Code


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

public class Main {
    /**/*from w w  w.java 2  s.c om*/
     * This method allows to merge 2 arrays
     *
     * @param <T> the generic type
     * @param firstArray the first array to merge
     * @param secondArray the second array to merge
     * @return merged array
     */
    public static <T> T[] mergeArrays(T[] firstArray, T[] secondArray) {

        int firstArrayLength = firstArray.length;
        int secondArrayLength = secondArray.length;

        @SuppressWarnings("unchecked")
        T[] mergedArray = (T[]) Array.newInstance(firstArray.getClass()
                .getComponentType(), firstArrayLength + secondArrayLength);
        System.arraycopy(firstArray, 0, mergedArray, 0, firstArrayLength);
        System.arraycopy(secondArray, 0, mergedArray, firstArrayLength,
                secondArrayLength);

        return mergedArray;
    }
}

Related Tutorials