In the code segment below, I want to create the array object inside the GenericStack class constructor. I understand why this is a problem. As per my understanding, "T" can be any class as far as the compiler is concerned. This class T can be an abstract class and hence cannot be instantiated. For example, java.lang.Number class is an abstract class and I could very well pass java.lang.Number for T.
My question now is the following:
Is there a way to tell the compiler (by some bounded parameters or perhaps something else) that the class that I am going to pass in place of T will be a concrete class that can be instantiated ? I know that I could easily create the array inside the main and then pass a reference but I find that to be a bit cluttered approach to implementing such requirement.
public class GenericStack<T> {
//Data for the stack is an array but can be changed to list.
public static final int stackSize = 10;
private T[] stackData;
private int tos;
public GenericStack(int size) {
stackData = new T[size]; // This line will error out
tos = -1;
}
public T pop() {
try {
return stackData[tos--];
} catch (Exception e) {
System.out.println("Stack empty.Cannot POP from an empty stack.");
return null;
}
}
public void push(T stackObj) {
try {
stackData[++tos] = stackObj;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Stack is full. Cannot push a element into a full stack.");
}
}
public static void main(String[] args) {
GenericStack<Integer> intStack = new GenericStack<Integer>(GenericStack.stackSize);
GenericStack<String> stringStack = new GenericStack<String>(GenericStack.stackSize);
}
}