Results 1 to 2 of 2
- 08-11-2010, 11:46 PM #1
Member
- Join Date
- Aug 2010
- Posts
- 4
- Rep Power
- 0
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!
- 08-12-2010, 12:13 AM #2
Member
- Join Date
- Aug 2010
- Posts
- 4
- Rep Power
- 0
Here's a way I can get around it:
package HelloWorldPkg;
public class MyStack2<T> {
private class Pod<T> {
T t;
Pod<T> next;
Pod(T t) {
this.t = t;
this.next = null;
}
}
Pod<T> head = null;
void push(T t) {
Pod<T> oldhead = head;
head = new Pod<T>(t);
head.next = oldhead;
return;
}
T pop() {
T t = head.t;
head = head.next;
return t;
}
public static void main( String[] args) {
MyStack2<Integer> stack = new MyStack2<Integer>();
stack.push( new Integer(3));
Integer rval = stack.pop();
System.out.printf( "rval = %d\n", rval.intValue());
return;
}
}
But, I don't like the fact that internally it's a linked list. There's no way of creating a block of contiguous memory to create references to T?
thanks.
Similar Threads
-
Generics
By bschmitt78 in forum Advanced JavaReplies: 3Last Post: 03-16-2010, 02:21 AM -
generics
By tascoa in forum Forum LobbyReplies: 2Last Post: 10-09-2008, 07:58 PM -
Help w/ generics
By Hollywood in forum New To JavaReplies: 2Last Post: 02-16-2008, 03:08 AM -
Generics
By sireesha in forum New To JavaReplies: 2Last Post: 01-10-2008, 11:08 PM -
Generics
By eva in forum New To JavaReplies: 2Last Post: 01-04-2008, 09:10 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks