Method to convert a Set Collection to a Array Collection - Java Collection Framework

Java examples for Collection Framework:Array Convert

Description

Method to convert a Set Collection to a Array Collection

Demo Code


import java.lang.reflect.Array;
import java.util.*;

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(toArray(collection)));
    }/*www. j  av  a  2  s  .  c  o m*/
    /**
     * Method to convert a Set Collection to a Array Collection
     * @param collection the Collection.
     * @param <T> generic type.
     * @return the Array Collection.
     */
    @SuppressWarnings("unchecked")
    public static <T> T[] toArray(Collection<T> collection) {
        if (isCollection(collection)) {
            if (collection instanceof List)
                return ListUtilities.toArray((List<T>) collection);
            //else if(collection instanceof TreeSet) return TreeSetUtilities.toArray((TreeSet<T>) collection);
            //else if(collection instanceof Set) return SetUtilities.toArray((Set<T>) collection);
            else
                return (T[]) Array.newInstance(Object.class, 0);
        } else {
            return ArrayUtilities.createAndPopulate(collection);
        }
    }
    /**
     * Method to check if a Object is a Collection or not.
     * @param ob the Object to inspect.
     * @return if true the class extend or implememnt Collection.
     */
    public static boolean isCollection(Object ob) {
        return ob instanceof Collection || ob instanceof Map;
        //return ob != null && isClassCollection(ob.getClass());
    }
}

Related Tutorials