集册 Java实例教程 创建指定类的数组,并使用指定Iterable的项目填充它。

创建指定类的数组,并使用指定Iterable的项目填充它。

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

515
创建指定类的数组,并用指定Iterable的项填充它。
/** 时   代     Java  公  众  号 - nowjava.com 提供 **/


//package com.nowjava;

import java.lang.reflect.Array;

import java.util.Arrays;


import java.util.LinkedList;

import java.util.List;


public class Main {

    /**

     * Creates an array of the specified class and populate it with items of the specified {@link Iterable}.

     */

    @SuppressWarnings("unchecked")

    public static <T> T[] arrayOf(Iterable<T> it, Class<T> clazz) {

        final List<T> list = listOf(it);

        final T[] result = (T[]) Array.newInstance(clazz, list.size());

        int i = 0;/*来 自 时   代    Java - nowjava.com*/

        for (final T t : it) {

            result[i] = t;

            i++;

        }

        return result;

    }


    /**

     * Returns a list form the the specified {@link Iterable}.

     * If the specified {@link Iterable} is yet a {@link List} than it

     * is returned as is, otherwise a brand new {@link List} is created.

     */

    public static <T> List<T> listOf(Iterable<T> it) {

        if (it instanceof List) {

            return (List<T>) it;

        }

        final List<T> result = new LinkedList<T>();

        for (final T t : it) {

      
展开阅读全文