Java Array Concatenate concatenate(@SuppressWarnings("unchecked") T[]... arrays)

Here you can find the source of concatenate(@SuppressWarnings("unchecked") T[]... arrays)

Description

This method copies all the Objects in all the given Object[]s into one large array in which the elements are ordered according to the order of the arrays given as arguments.

License

Open Source License

Parameter

Parameter Description
arrays is the list of <tt>Object[]</tt>s to be concatenated into one large array.

Return

one large Object[] containing all the elements of the given arrays in the order given.

Declaration

public static <T> T[] concatenate(@SuppressWarnings("unchecked") T[]... arrays) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.ArrayList;

public class Main {
    /** This method copies all the <tt>Objects</tt> in all the given <tt>Object[]</tt>s into one large array in which the elements are ordered according to the order of the
     * arrays given as arguments./* w w w  .  j  av  a  2s  .c  o  m*/
     * 
     * @param arrays
     *            is the list of <tt>Object[]</tt>s to be concatenated into one large array.
     * @return one large <tt>Object[]</tt> containing all the elements of the given <b><tt>arrays</b></tt> in the order given. */
    public static <T> T[] concatenate(@SuppressWarnings("unchecked") T[]... arrays) {
        // find the sum of the lengths of all the arrays
        int new_length = 0;
        for (T[] array : arrays)
            new_length += array.length;

        // create the new array
        /* NOTE: I had to make an ArrayList and convert it to an array because you can't make arrays of a generic type */
        @SuppressWarnings("unchecked")
        T[] result = (T[]) new ArrayList<T>(new_length).toArray();

        // copy all the Objects from the arrays into the new array
        int counter = 0; // counter is necessary because each array is not necessarily the same size
        for (int i = 0; i < arrays.length; i++)
            for (int j = 0; j < arrays[i].length; j++) {
                result[counter] = arrays[i][j];
                counter++;
            }

        return result;
    }
}

Related

  1. concatArrays(String[] A, String[] B)
  2. concatArrays(String[] array, String[] arrayToBeConcat)
  3. concatArrays(T[] first, T[] second)
  4. concatArrays(T[] first, T[] second)
  5. concatByteArrays(final byte[] array1, final byte[] array2)
  6. concatenate(byte[] a, byte[] b)
  7. concatenate(double[] p1, double[] p2)
  8. concatenate(float[][] a, float[][] b, int dim)
  9. concatenate(int[]... arrays)