集册 Java实例教程 方法将数组转换为对象数组。

方法将数组转换为对象数组。

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

339
方法将数组转换为对象数组。
/*n o w j a v a . c o m - 时代Java 提供*/

import java.lang.reflect.Array;

import java.util.*;


public class Main{

    /**

     * Method to convert a aarray to a Object array.

     * @param primitiveArray the primitive array to convert.

     * @param <T> generic type.

     * @return a Object array.

     */

    public static <T> Object[] toObjectArray(T[] primitiveArray) {

        List<Object> objectList = new ArrayList<>();

        objectList.addAll(Arrays.asList(primitiveArray));

        return toArray(objectList);

    }

    public static <T> Object[] toObjectArray(List<T> primitiveList) {

        List<Object> objectList = new ArrayList<>();

        objectList.addAll(primitiveList);

        return toArray(objectList);

    }

    /**

     * 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)// from 时代Java公众号 - nowjava.com

                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);

        } else {

            return ArrayUtilities.createAndPopulate(collection);

        }

    }

    
展开阅读全文