Returns an array containing all of the elements in the given collection. - Java java.util

Java examples for java.util:Collection to Array

Description

Returns an array containing all of the elements in the given collection.

Demo Code

/*******************************************************************************
 * Copyright (c) 2011 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors://w  w  w  . j  a  v a 2s  .  co m
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
//package com.java2s;
import java.lang.reflect.Array;
import java.util.Collection;

public class Main {
    public static void main(String[] argv) {
        Collection collection = java.util.Arrays.asList("asdf",
                "java2s.com");
        Class clazz = String.class;
        System.out.println(java.util.Arrays.toString(toArray(collection,
                clazz)));
    }

    /**
     * Returns an array containing all of the elements in the given collection. This is a
     * compile-time type-safe alternative to {@link Collection#toArray(Object[])}.
     * 
     * @param collection the source collection
     * @param clazz the type of the array elements
     * @param <A> the type of the array elements
     * @return an array of type <code>A</code> containing all of the elements in the given
     *         collection
     * 
     * @throws NullPointerException if the specified collection or class is null
     * 
     * @see <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7023484">Sun bug 7023484</a>
     */
    public static <A> A[] toArray(Collection<? extends A> collection,
            Class<A> clazz) {
        Object array = Array.newInstance(clazz, collection.size());
        @SuppressWarnings("unchecked")
        A[] typedArray = collection.toArray((A[]) array);
        return typedArray;
    }
}

Related Tutorials