Home > Java > javaTutorial > body text

Generics in Java programming ideas implement a stack class

高洛峰
Release: 2017-01-18 11:03:28
Original
1313 people have browsed 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 articles related to generic implementation of a stack class in Java programming ideas, 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!