Home



2018/10 - Type Erasure - Why you can't create generic arrays in Java

Hi folks,

Type erasure in Java is used to determine typing at runtime, when generics are involved. It basically means that when you type:

 

List x = new ArrayList<T>();

 

Java figures out what the array list's type is. However, if we try to create a generic array:

 

T[] genericArray = new T[];

 

We find that the code won't even compile because Java specifically forbids the use of generics for basic arrays. So why is this the case and why should you care? Well for one, it'll further your knowledge of generics, and for another you'll know that you'll have to use a generic collection instead of a generic array (Or one of these abominations, which isn't really a generic array anyway).

The mains reasons that you cannot create a generic array in Java are:

  1. Generics rely on not typing your objects/collections/etc at compile time. Java will wait until your program is actually running before saying "Okay! So what type should this generic thing be?"
  2. An ArrayList is invariant, while an Array is covariant. This basically translates to Arrays remembering their types at runtime because they don't change (Unlike ArrayLists, which can). And how can a type remember that it is generic? Well it can't since T isn't a type, T is the absence of a type until later in the program. 

The main takeaway here is that you should keep an eye out for concepts in Java that are covariant and invariant, as this will affect whether you can use generics or not.

Cheers,

Marc

 

Further reading:

https://stackoverflow.com/questions/529085/how-to-create-a-generic-array-in-java

https://www.baeldung.com/java-type-erasure

https://www.quora.com/Why-does-Java-prohibit-generic-array-creation

https://www.quora.com/Why-cant-we-initialize-array-of-generic-object

https://programming.guide/java/generic-array-creation.html

http://www.tothenew.com/blog/why-is-generic-array-creation-not-allowed-in-java/