集册 Java实例教程 将各种数据结构转换为数组

将各种数据结构转换为数组

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

473
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
将各种数据结构转换为数组


//package com.book2s;
/** 
 来自 N o  w  J a v a . c o m - 时  代  Java**/

import java.util.ArrayList;

import java.util.Collection;


import java.util.Iterator;

import java.util.List;


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(asArray(collection)));

    }


    @SuppressWarnings("unchecked")

    public static <E> E[] asArray(final Collection<? extends E> collection) {//from n  o  w  j  a  v  a . c o m

        return collection.toArray((E[]) new Object[collection.size()]);

    }


    @SuppressWarnings("unchecked")

    public static <E> E[] asArray(final Object... array) {

        final E[] elements = (E[]) new Object[array.length];

        for (int i = 0; i < array.length; i++) {

            elements[i] = (E) array[i];

        }

        return elements;

    }


    public static <E> List<E> asList(

            @SuppressWarnings("unchecked") final E... array) {

        List<E> list = new ArrayList<>(array.length);

        for (E element : array) {

            list.add(element);

        }

        return list;

    }


    public static <E> List<E> asList(final Iterator<? extends E> iterator) {

        List<E> list = new ArrayList<>();

        while (iterator.hasNext()) {

            list.add(iterator.next());

        }

        return list;

    }


    public static <E> String toString(Iterator<E> iterator) {

        if (iterator == null || !iterator.hasNext()) {

     
展开阅读全文