我想通过Java中的一个类来实现FIFO。
这样的类已经存在了吗?如果没有,我如何实现我自己的?
笔记
我在这里找到了一个类http://www.dcache.org/manuals/cells/docs/api/dmg/util/Fifo.html,但它没有包含dmg.util.*。我甚至不知道这样的包是否存在。
发布于 2012-03-06 16:52:49
您正在寻找实现Queue interface的任何类,不包括PriorityQueue
和PriorityBlockingQueue
,它们不使用先进先出算法。
可能使用add
(在末尾添加1)和removeFirst
(从前面移除1并返回它)的LinkedList是最容易使用的。
例如,下面的程序使用LinkedList来排队并检索PI的数字:
import java.util.LinkedList;
class Test {
public static void main(String args[]) {
char arr[] = {3,1,4,1,5,9,2,6,5,3,5,8,9};
LinkedList<Integer> fifo = new LinkedList<Integer>();
for (int i = 0; i < arr.length; i++)
fifo.add (new Integer (arr[i]));
System.out.print (fifo.removeFirst() + ".");
while (! fifo.isEmpty())
System.out.print (fifo.removeFirst());
System.out.println();
}
}
或者,如果您知道只想将其视为队列(没有链表的额外功能),则可以只使用Queue
接口本身:
import java.util.LinkedList;
import java.util.Queue;
class Test {
public static void main(String args[]) {
char arr[] = {3,1,4,1,5,9,2,6,5,3,5,8,9};
Queue<Integer> fifo = new LinkedList<Integer>();
for (int i = 0; i < arr.length; i++)
fifo.add (new Integer (arr[i]));
System.out.print (fifo.remove() + ".");
while (! fifo.isEmpty())
System.out.print (fifo.remove());
System.out.println();
}
}
这样做的好处是,您可以用提供Queue
接口的任何类替换底层的具体类,而不必过多地更改代码。
基本更改是将fifo
的类型更改为Queue
,并使用remove()
而不是removeFirst()
,后者对于Queue
接口不可用。
仍然可以调用isEmpty()
,因为它属于Collection
接口,而Queue
是它的派生接口。
发布于 2012-03-06 16:53:03
试试ArrayDeque
或LinkedList
,它们都实现了Queue
接口。
http://docs.oracle.com/javase/6/docs/api/java/util/ArrayDeque.html
https://stackoverflow.com/questions/9580457
复制相似问题