集册 Java实例教程 基于开始索引和结束索引将列表转换为数组的新副本。

基于开始索引和结束索引将列表转换为数组的新副本。

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

377
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
基于开始索引和结束索引将列表转换为数组的新副本。


//package com.nowjava;

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

import java.util.Collection;


import java.util.List;

import java.util.Map;


public class Main {

    public static void main(String[] argv) {

        List list = java.util.Arrays.asList("asdf", "nowjava.com");

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

    }


    /**

     * Converts a list to a new copy of array based on the start index and end index.

     * 

     * @param list

     * @param startIndex

     * @param endIndex

     * @return

     */

    @SuppressWarnings({ "unchecked", "cast" })

    public static final <T> T[] toArray(List<T> list, int startIndex,

            int endIndex) {

        if (isEmpty(list)) {

            return (T[]) list.toArray();

        }

        List<T> subList = list.subList(startIndex, endIndex);/**时代Java公众号 - nowjava.com**/

        return (T[]) subList.toArray((T[]) java.lang.reflect.Array

                .newInstance(list.get(0).getClass(), subList.size()));

    }


    public static final <T> T[] toArray(List<T> list) {

        return toArray(list, 0, list.size());

    }


    /**

     * This is a convenience method that returns true if the specified collection is null or empty

     * 

     * @param <T>

     *            Any type of object

     * @param collection

     * @return

     */

    public static <T> boolean isEmpty(Collection<T> collection) {

        return collection == null || collection.isEmpty();

    }


    /**

     * This is a convenience method that returns true if the specified map is null or empty

     * 

     * @param <T>

     *            any type of key

     * @param <U>

     *            any type of value

     * @param map

     * @return

     */

    public static <T, U> 
展开阅读全文