Java Generics – No Array

Java Generics - No Array

This topic is about Java Generics – No Array.

Arrays of parameterized types are not allowed.

//Cannot create a generic array of Box<Integer>
Box<Integer>[] arrayOfLists = new Box<Integer>[2]; 

Because compiler uses type erasure, the type parameter is replaced with Object and user can add any type of object to the array. And at runtime, code will not able to throw ArrayStoreException.

// compiler error, but if it is allowed
Object[] stringBoxes = new Box<String>[];
  
// OK
stringBoxes[0] = new Box<String>();  

// An ArrayStoreException should be thrown,
//but the runtime can't detect it.
stringBoxes[1] = new Box<Integer>();  

In this topic we learned about Java Generics – No Array. To know more, Click Here.

Leave a Reply