Java Articles


Arrays of parameterized type

by Ram Satish


In this article, I will show you why you can’t create an array of parameterized types.

In the example below, I try creating an array of parameterized type but the compiler will treat this as an error.

Node<Integer>[] intNodeArray = new Node<Integer>[3];

Cannot create a generic array of Node<Integer>

Before we figure out why Java Generics doesn’t support array creation of parameterized types, we need to know what is it being covariant.


Arrays are covariant

An array of supertype references is a supertype of an array of subtype references.
That is, Object[] holding references of Objects is a supertype of String[] array holding an array of string references so below is allowed by the compiler. Even runtime allows it as Object is supertype of String.

Object[] objArray = new String[3];
objArray[0] = new String();

Why creation of an array of parameterized type is not allowed?

Assuming compiler allows creation of array of parameterized type, it would be legal to assign the Node<Integer>[] array to an Object[] array since arrays are covariant.
Node<Integer>[] intNodeArray = new Node<Integer>[]{new Node(1), new Node(2)}; throws error but for now let us assume it is allowed.
Now we will assign a Node object of different type to our object array. You can see in the example below, I have assigned a Node<String> object to the first element of an object array which is supposed to be holding Node<Integer> objects. Once this is done, we will end up in an unacceptable situation.

    public void testTypedArray() {
Node<Integer>[] intNodeArray = new Node<Integer>[]{new Node(1), new Node(2)};//throws error
Integer i = (Integer) nodeArray[0].getValue();

private void arrayCovariant(Node<Integer>[] inNodeStrArray) {
Object[] oa = inNodeStrArray;
oa[0] = new Node<String>("Will fail at runtime");

Integer i = (Integer) nodeArray[0].getValue() will throw ClassCastException.
In order to prevent this kind of type-unsafe situation, arrays of parameterized type are not allowed.