Java tutorial
//package com.java2s; /* * Copyright (c) MuleSoft, Inc. All rights reserved. http://www.mulesoft.com * The software in this package is published under the terms of the CPAL v1.0 * license, a copy of which has been included with this distribution in the * LICENSE.txt file. */ import java.lang.reflect.Array; import java.util.Collection; import java.util.Iterator; public class Main { /** * Creates an array of the given Collection's elements, but with the given * <code>Class</code> as element type. Useful for arrays of objects that * implement multiple interfaces and a "typed view" onto these objects is * required. * * @param objects a Collection of objects * @param clazz the desired service type of the new array * @return <code>null</code> when objects is <code>null</code>, or a new * array containing the elements of the source array which is typed to * the given <code>clazz</code> parameter. * @throws IllegalArgumentException if the <code>clazz</code> argument is * <code>null</code>. * @throws ArrayStoreException if the elements in <code>objects</code> cannot * be cast to <code>clazz</code>. */ public static <T> T[] toArrayOfComponentType(Collection objects, Class<T> clazz) { if (objects == null) { return null; } if (clazz == null) { throw new IllegalArgumentException("Array target class must not be null"); } if (objects.isEmpty()) { return (T[]) Array.newInstance(clazz, 0); } int i = 0, size = objects.size(); T[] result = (T[]) Array.newInstance(clazz, size); Iterator iter = objects.iterator(); while (i < size && iter.hasNext()) { result[i++] = (T) iter.next(); } return result; } }