Home > Java > javaTutorial > Generics in Java programming ideas implement a stack class Share

Generics in Java programming ideas implement a stack class Share

高洛峰
Release: 2017-01-24 15:17:07
Original
1637 people have browsed it

I think the author wrote it so well that I have to save it.

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
*/
Copy after login

For more generics in Java programming ideas, implement a stack class. To share related articles, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template