Convert list of arrays of objects to array of arrays of objects. - Java Collection Framework

Java examples for Collection Framework:Array Convert

Description

Convert list of arrays of objects to array of arrays of objects.

Demo Code


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

public class Main {
    public static void main(String[] argv) throws Exception {
        List list = java.util.Arrays.asList("asdf", "java2s.com");
        Class arrayElements = String.class;
        System.out.println(java.util.Arrays
                .toString(listOfArraysToDoubleArray(list, arrayElements)));
    }/*from ww  w. jav a 2 s  . c  om*/

    /**
     * Convert list of arrays of objects to array of arrays of objects.
     * 
     * @param <T>
     *                type of the array
     * 
     * @param list
     *                {@link List}, list of arrays
     * @param arrayElements
     *                Class, class of the array type
     * @return Object
     */
    @SuppressWarnings("unchecked")
    public static <T> T[][] listOfArraysToDoubleArray(List<T[]> list,
            Class<T> arrayElements) {
        T[][] result = (T[][]) Array.newInstance(arrayElements, new int[] {
                list.size(), 0 });
        int i = 0;
        for (T[] array : list) {
            result[i++] = array;
        }
        return result;
    }
}

Related Tutorials