Due to the implementation of Java generics, you can't have code like this:
public class GenericSet<E> {
private E a[];
public GenericSet() {
a = new E[INITIAL_ARRAY_LENGTH]; // error: generic array creation
}
}
How can I implement this while maintaining type safety?
One way to do it is :
import java.lang.reflect.Array;
class Stack<T> {
public Stack(Class<T> clazz, int capacity) {
array = (T[])Array.newInstance(clazz, capacity);
}
private final T[] array;
}
But it is very confusing to understand