How to create a type safe generic array in java?

arrays, generics, java

Solution

The `Array.newInstance(..)` method has a return type of `Object`. As such, you cannot directly assign it to anything other than `Object`. You therefore need a cast.

The method delegates to a `native` method which

Creates a new array with the specified component type and length

Therefore it is creating an array of type `T`.

The type safety, assuming `array` is declared as

T[] array;

, is guaranteed by the `Class<T>` parameter and the cast using the same type variable.

You should add the

@SuppressWarnings("unchecked")

with a comment explaining the above reason in your source code. Always comment why a cast whose warning you are suppressing is safe.

Problem

I want to create a generic array in java maintaining the type safety usually offered by Java. I am using this code : ``` class Stack<T> { private T[] array = null; public Stack(Class<T> tClass, int size) { maximumSize = size; // type unsafe //array = (T[])new Object[maximumSize]; this.array = (T[])java.lang.reflect.Array.newInstance(tClass,maximumSize); } ``` is this code type safe? ans if so, why? why if it is type safe I need a cast?

Original source