Java: How can I dynamically create an array of a specified type based on the type of an object?


I would like to take a passed List that I know is homogeneous and from it create an array of the same type as the elements within it.

Something like...

List<Object> lst = new ArrayList<Object>;

lst.add(new Integer(3));

/// somewhere else ...

assert(my_array instanceof Integer[]);

The conversion would happen runtime, while the type is lost at compile time. So you should do something like:

public <T> T[] toArray(List<T> list) {
    Class clazz = list.get(0).getClass(); // check for size and null before
    T[] array = (T[]) java.lang.reflect.Array.newInstance(clazz, list.size());
    return list.toArray(array);

But beware that the 3rd line above may throw an exception - it's not typesafe.