[ 永遠的UNIX::UNIX技術資料的寶庫 ]   GB | BIG5

首頁 > 編程技術 > Java > 正文
編寫一個JAVA的隊列類
本文出自:www.chinajavaworld.com 作者: 樑健 (2001-12-31 07:10:00)
隊列是設計程序中常用的一種數據結構。它類似日常生活中的排隊現象,採用一種被稱為
“先進先出”(LIFO)的存儲結構。數據元素只能從隊尾進入,從隊首取出。在隊列中,
數據元素可以任意增減,但數據元素的次序不會改變。每當有數據元素從隊列中被取出,
面的數據元素依次向前移動一位。所以,任何時候從隊列中讀到的都是隊首的數據。
根據這些特點,對隊列定義了以下六種操作:
enq(x) 向隊列插入一個值為x的元素;
deq() 從隊列刪除一個元素;
front() 從隊列中讀一個元素,但隊列保持不變;
empty() 判斷隊列是否為空,空則返回真;
clear() 清空隊列;
search(x) 查找距隊首最近的元素的位置,若不存在,返回-1。

Vector類是JAVA中專門負責處理對象元素有序存儲和任意增刪的類,因此,用Vector
可以快速實現JAVA的隊列類。

public class Queue extends java.util.Vector {
public Queue() {
super();

public synchronized void enq(Object x) {
super.addElement(x);

public synchronized Object deq() {
/* 隊列若為空,引發EmptyQueueException異常 */
if( this.empty() )
throw new EmptyQueueException();
Object x = super.elementAt(0);
super.removeElementAt(0);
return x;

public synchronized Object front() {
if( this.empty() )
throw new EmptyQueueException();
return super.elementAt(0);

public boolean empty() {
return super.isEmpty();
}
public synchronized void clear() {
super.removeAllElements();

public int search(Object x) {
return super.indexOf(x);

}

public class EmptyQueueException extends java.lang.RuntimeException {
public EmptyQueueException() {
super();

}

以上程序在JDK1.1.5下編譯通過
(http://www.fanqiang.com)
    進入【UNIX論壇

相關文章
 

★  樊強制作 歡迎分享  ★