Java examples for Collection Framework:Array Convert
Convert various data structure as Array
//package com.book2s; 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))); }//w w w . ja v a 2 s . c o m @SuppressWarnings("unchecked") public static <E> E[] asArray(final Collection<? extends E> collection) { 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()) { return "[]"; } StringBuilder builder = new StringBuilder(); builder.append('['); while (iterator.hasNext()) { builder.append(iterator.next()).append(',').append(' '); } return builder.append(']').toString(); } }