PositiveGuy PositiveGuy - 26 days ago 6
Java Question

What is Object[]?

I was taking a look at this code.

What is this doing?

(T[])(new Object[DEFAULT_CAPACITY]);


I am not as familiar with Java and all the intricacies around the Object superclass and how you can use it. But I assume that's creating basically a generic array only that it's an array based on the super class Type Object?

Answer

The line contents = (T[])(new Object[DEFAULT_CAPACITY]) only serves to initialise T[] contents with DEFAULT_CAPACITY number of Object.

The Object[] array is cast to T[] since you cannot initialise generic arrays in Java. The cast of Object to T compiles and runs as all Java objects extend Object.

It should be noted that the explicit cast of Object[] to T[] is considered unsafe and will result in a compiler warning. For more information on unchecked array casts in Java, see: Creating generic array in Java via unchecked type-cast.