Type Erasure(ClassCastException)

Why am I having an error when I compile this? AFAIK Number is a derivative of Object superclass right? Then it should be downcasted. I’m confused.

First of all, the generics go the other direction: a Number is an Object, but an Object is not a number. For example, this would also not work:

Number number = new Object();

But this would:

Object number = (Number) 10;

That being said, you probably noticed that Java does not let you create a generic array with the trivial syntax like this:

T[] genericArray = new T[10];

This is partly due to type erasure.

So, we have to work around that and two ways to work around it are (1) passing the class (at which point you might as well use that to type the array) or (2) skip out on using array altogether (for example, use an ArrayList).

Here is one way to create a “generic” array if you can pass the class:

Class clazz = Integer.java; // for example
int capacity = 10; // for example 
T[] genericArray = (T[]) Array.newInstance(clazz, capacity);

That being said, I doubt you need a generic array given that you have restricted your list to holding Number objects, so you can just make an array of numbers:

Number[] elements = new Number[4];
2 Likes