Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instantiate a Java array given an array type at runtime?

In the Java collections framework, the Collection interface declares the following method:

<T> T[] toArray(T[] a)

Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array. If the collection fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this collection.

If you wanted to implement this method, how would you create an array of the type of a, known only at runtime?

like image 841
Sam Avatar asked Sep 16 '08 21:09

Sam


People also ask

How do we instantiate an array in Java?

We declare an array in Java as we do other variables, by providing a type and name: int[] myArray; To initialize or instantiate an array as we declare it, meaning we assign values as when we create the array, we can use the following shorthand syntax: int[] myArray = {13, 14, 15};

How do you instantiate an array of arrays?

Initialize Array of Arrays To initialize an array of arrays, you can use new keyword with the size specified for the number of arrays inside the outer array. int[][] numbers = new int[3][]; specifies that numbers is an array of arrays that store integers.

How do you declare an array in runtime?

An array can also be initialized at runtime using scanf() function. This approach is usually used for initializing large array, or to initialize array with user specified values.


3 Answers

Use the static method

java.lang.reflect.Array.newInstance(Class<?> componentType, int length)

A tutorial on its use can be found here: http://java.sun.com/docs/books/tutorial/reflect/special/arrayInstance.html

like image 164
user9116 Avatar answered Oct 28 '22 13:10

user9116


By looking at how ArrayList does it:

public <T> T[] toArray(T[] a) {
    if (a.length < size)
        a = (T[])java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size);
    System.arraycopy(elementData, 0, a, 0, size);
    if (a.length > size)
        a[size] = null;
    return a;
}
like image 23
SCdF Avatar answered Oct 28 '22 13:10

SCdF


Array.newInstance(Class componentType, int length)
like image 36
Arno Avatar answered Oct 28 '22 13:10

Arno