I was taking a look at this code.
What is this doing?
(T[])(new Object[DEFAULT_CAPACITY]);
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.