Java examples for Collection Framework:Array Convert
Method to convert an array to a Object array.
import java.lang.reflect.Array; import java.util.*; public class Main{ /**//from w w w . j a v a 2s . c o m * Method to convert a aarray to a Object array. * @param primitiveArray the primitive array to convert. * @param <T> generic type. * @return a Object array. */ public static <T> Object[] toObjectArray(T[] primitiveArray) { List<Object> objectList = new ArrayList<>(); objectList.addAll(Arrays.asList(primitiveArray)); return toArray(objectList); } public static <T> Object[] toObjectArray(List<T> primitiveList) { List<Object> objectList = new ArrayList<>(); objectList.addAll(primitiveList); return toArray(objectList); } /** * 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()); } }