集册 Java实例教程 如果它是一个,则将Iterable强制转换为Collection。

如果它是一个,则将Iterable强制转换为Collection。

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

677
将Iterable强制转换为集合(如果它是集合)。

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

//package com.nowjava;

import java.util.ArrayList;

import java.util.Collection;


import java.util.Iterator;

import java.util.List;


public class Main {

    /**

     * Casts the {@link Iterable} to a {@link Collection} if it is one.

     * Otherwise it makes a shallow copy.

     *

     * @param iterable

     * @return the content as a collection.

     */

    public static <T> Collection<T> asCollection(Iterable<T> iterable) {

        return (iterable instanceof Collection) ? (Collection<T>) iterable

                : shallowCopy(iterable);/*来自 时代Java*/

    }


    /**

     * Generates a new {@link Iterable} that references the items of the given

     * {@link Iterable}.

     *

     * @param <T>

     *          The collection item fieldClass.

     * @param ori

     *          The iterable to get a shallow copy for.

     * @return The shallow copy.

     */

    public static <T> List<T> shallowCopy(Iterable<T> ori) {

        ArrayList<T> copy = new ArrayList<T>();


        for (T t : ori) {

            copy.add(t);

        }


        return copy;

    }


    /**

     * Generates a collection that references the items of the given

     * {@link Iterator}.<br>

     * The iterator should be at its start position.

     *

     * @param <T>

     *          The collection item fieldClass.

     * @param iter

     *          The iterator to get a shallow copy for.

     * @return The shallow copy.

     */

    
展开阅读全文