How do they do it? Generics and my own stack.
Hello. I am going through the java tutorial online at the oracle website.
In the section about Generics, it states that you cannot create a Generic array. So the following code will work, but not the commented out store:
package HelloWorldPkg;
import java.util.Vector;
public class MyStack<T> {
// T[] store = new T[some_size]; // Does not work.
Vector<T> store = new Vector<T>();
int last = 0;
public MyStack() {
}
public void push( T t) {
store.add(t);
}
public T pop() {
return store.remove(store.size()-1);
}
public static void main( String[] args) {
MyStack<Integer> stack = new MyStack<Integer>();
stack.push(new Integer(3));
Integer i = stack.pop();
System.out.println( "Integer returned is: " + i);
return;
}
}
If I change the above code so that store is type T[] and I change push/pop accordingly, the java compiler complains about not being able to do new T[]. And that's because type erasure.
So how does one address this limitation (or limitation in my brain)?
So, to get around this, I changed store to Vector<T>.
but then, how does Vector<T> get around this problem?
I thought I could make store type Object[], but that eventually leads to an explicit cast to T, which is not allowed either due to type erasure.
Anyways, I'd like some enlightenment.
thanks!