DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> JavaScript綜合知識 >> Java編程思想裡的泛型實現一個堆棧類 分享
Java編程思想裡的泛型實現一個堆棧類 分享
編輯:JavaScript綜合知識     

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

對這個例子的理解:

//類型參數不能用基本類型,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
*/

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved