Converts a collection to a primitive array of a given type. - Java Collection Framework

Java examples for Collection Framework:Array Convert

Description

Converts a collection to a primitive array of a given type.

Demo Code


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

public class Main {
    public static void main(String[] argv) {
        Class type = String.class;
        Collection collection = java.util.Arrays.asList("asdf",
                "java2s.com");
        System.out.println(java.util.Arrays.toString(toArray(type,
                collection)));// w  ww. j a v  a 2 s.c o m
    }

    /**
     * Converts a collection to a primitive array of a given type.
     *
     * @param type       type of array to create
     * @param collection collection to convert, must contain items that extend T
     * @param <T>        type of array to create
     * @return primitive array of type T
     */
    public static <T> T[] toArray(Class<T> type,
            Collection<? extends T> collection) {
        T[] array = (T[]) Array.newInstance(type, collection.size());
        int i = 0;
        for (T item : collection) {
            array[i++] = item;
        }

        return array;
    }
}

Related Tutorials