集册 Java实例教程 方法将集合转换为数组集合

方法将集合转换为数组集合

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

608
方法将集合转换为数组集合
//from N o w  J a v a  .   c o m


import java.lang.reflect.Array;

import java.util.*;


public class Main{

    public static void main(String[] argv){

        Collection collection = java.util.Arrays.asList("asdf","book2s.com");

        System.out.println(java.util.Arrays.toString(toArray(collection)));

    }

    /**

     * Method to convert a Set Collection to a Array Collection

     * @param collection the Collection.

     * @param <T> generic type.

     * @return the Array Collection.

     */

    @SuppressWarnings("unchecked")

    public static <T> T[] toArray(Collection<T> collection) {

        if (isCollection(collection)) {

            if (collection instanceof List)

                return ListUtilities.toArray((List<T>) collection);

            //else if(collection instanceof TreeSet) return TreeSetUtilities.toArray((TreeSet<T>) collection);

            //else if(collection instanceof Set) return SetUtilities.toArray((Set<T>) collection);

            else

                return (T[]) Array.newInstance(Object.class, 0);/**来 自 时代Java公众号**/

        } else {

            return ArrayUtilities.createAndPopulate(collection);

        }

    }

    /**

     * Method to check if a Object is a Collection or not.

     * @param ob the Object to inspect.

     * @return if true the class extend or implememnt Collection.

     */

    
展开阅读全文