Skip to content
Advertisement

ClassCastException when declaring class generic as string

I have a GenericList class that must initialise an array with type but it force me to declare it as Object in compile time. When I declare the generic as String in Main, the program stops with ClassCastException when i assign the list.items to a variable called items, which compile time also recognise it as String[]. Error is like this:

JavaScript

Why and how to solve this? Thank you.

JavaScript

JavaScript

Advertisement

Answer

You must to inject explicitly the array constructor for T type.

E.g. move your new T[10] as

JavaScript

And create the object injecting the constructor

JavaScript

Now all works

JavaScript

(Note: with T[] items = (T[]) new Object[10] you are not creating a T array, you are creating an Object array casting to a T array, which is incorrect)

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement