Understanding of this example:
//Type parameters cannot use basic types. T and U are actually the same type.
//Every time new data is placed, it becomes a new top. Push the original top down one level and establish a link through the pointer.
//The end sentinel is a node created by the default constructor that is consistent with end() returning true.
//: generics/LinkedStack.java // A stack implemented with an internal linked structure. package generics; public class LinkedStack<T> { private static class Node<U> { U item; Node<U> next; Node() { item = null; next = null; } Node(U item, Node<U> next) { this.item = item; this.next = next; } boolean end() { return item == null && next == null; } } private Node<T> top = new Node<T>(); // End sentinel public void push(T item) { top = new Node<T>(item, top); } public T pop() { T result = top.item; if(!top.end()) top = top.next; return result; } public static void main(String[] args) { LinkedStack<String> lss = new LinkedStack<String>(); for(String s : "Phasers on stun!".split(" ")) lss.push(s); String ss; while((ss = lss.pop()) != null) System.out.println(ss); //----- if put integer into the LinkedList LinkedStack<Integer> lii = new LinkedStack<Integer>(); for(Integer i = 0; i < 10; i++){ lii.push(i); } Integer end; while((end = lii.pop()) != null) System.out.println(end); //----- integer test end! } } /* Output: stun! on Phasers */
For more articles related to generic implementation of a stack class in Java programming ideas, please pay attention to the PHP Chinese website!