首頁 > Java > java教程 > 主體

Java程式設計思想裡的泛型實作一個堆疊類別 分享

高洛峰
發布: 2017-01-24 15:17:07
原創
1575 人瀏覽過

覺得作者寫得太好了,只好收藏一下。

對這個例子的理解:

//型態參數不能用基本型,T和U其實是同型。

//每次放新資料都成為新的top,把原來的top往下壓一級,透過指針建立連結。

//末端哨兵既是預設建構器所建立的符合end()回傳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
*/
登入後複製

更多Java程式設計思想裡的泛型實作一個堆疊類別 分享相關文章請關注PHP中文網!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!