Convert the specified collection to an array which contains all elements in the collection - Android java.util

Android examples for java.util:Collection Contains

Description

Convert the specified collection to an array which contains all elements in the collection

Demo Code


import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import com.elminster.common.util.Messages.Message;

public class Main{
    public static void main(String[] argv){
        Collection collection = java.util.Arrays.asList("asdf","book2s.com");
        System.out.println(collection2Array(collection));
    }//w ww . j  a  v  a 2s.co  m
    /**
     * Convert the specified collection to an array which contains all elements in
     * the collection
     * 
     * @param collection
     *          the specified collection
     * @return an array which contains all elements in the collection
     */
    public static Object collection2Array(Collection<?> collection) {
        if (null == collection) {
            return new Object[0];
        }
        Object[] array = null;
        Iterator<?> iterator = collection.iterator();
        while (iterator.hasNext()) {
            Object obj = iterator.next();
            Class<?> clazz = obj.getClass();
            array = (Object[]) Array.newInstance(clazz, collection.size());
            int i = 0;
            iterator = collection.iterator();
            while (iterator.hasNext()) {
                array[i++] = iterator.next();
            }
        }
        return array;
    }
}

Related Tutorials