集册 Java实例教程 将集合转换为给定类型的基元数组。

将集合转换为给定类型的基元数组。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

342
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
将集合转换为给定类型的基元数组。

/* from 
时   代     Java  公  众  号 - nowjava.com*/

//package com.nowjava;

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",

                "nowjava.com");

        System.out.println(java.util.Arrays.toString(toArray(type,

                collection)));

    }


    /**

     * 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) {
            /* 
             来自 
            *N o w  J a v a  .   c o m*/

        T[] array = (T[])
展开阅读全文