class LinkedListNode{ public LinkedListNode(T newData) { data = newData; } LinkedListNode next = null; T data; }; public class LinkedList { // etc };
I'm told that generics in Java are sorta bad because they use type erasure. This is when the compiler "erases" the types of generic classes, so it's compatible with any old non-generic classes. This means if a class has type T, you cannot reference T anywhere in your code, like you could with C++ templates. In fact, the other day one of my coworkers was complaining that they have to duplicate code that creates a new class of a generic type just for this reason.
public class Stackextends LinkedList { public Stack() { super(); } public void push(LinkedListNode node) { node.next = _root; _root = node; } public LinkedListNode pop() { LinkedListNode ret = _root; _root = _root.next; return ret; } }
and then a queue is trivial:
public class Queueextends LinkedList { public void enqueue (LinkedListNode node) { insert(node); } public LinkedListNode dequeue () { LinkedListNode ret = _root; _root = _root.next; return ret; } }
No comments:
Post a Comment