Java中的FIFO类 [英] FIFO class in Java

查看:63
本文介绍了Java中的FIFO类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过Java中的类实现FIFO.

I want to implement FIFO through a class in Java.

这样的类已经存在了吗?如果没有,我该如何实施自己的计划?

Does such a class already exist? If not, how can I implement my own?

注意

我在这里 http://www.dcache.org/手册/cells/docs/api/dmg/util/Fifo.html ,但其中不包含dmg.util.*.我不知道这样的包是否存在.

I found a class here http://www.dcache.org/manuals/cells/docs/api/dmg/util/Fifo.html, but it doesn't contain dmg.util.*. I don't know if such a package even exists.

推荐答案

您正在寻找实现

You're looking for any class that implements the Queue interface, excluding PriorityQueue and PriorityBlockingQueue, which do not use a FIFO algorithm.

可能是使用 LinkedList >(在末尾添加一个)和removeFirst(从前面删除一个并返回它)是最容易使用的一个.

Probably a LinkedList using add (adds one to the end) and removeFirst (removes one from the front and returns it) is the easiest one to use.

例如,这是一个使用LinkedList排队并检索PI数字的程序:

For example, here's a program that uses a LinkedList to queue and retrieve the digits of 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界面本身:


Alternatively, if you know you only want to treat it as a queue (without the extra features of a linked list), you can just use the Queue interface itself:

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接口的任何类替换基础的具体类,而不必过多地更改代码.

This has the advantage of allowing you to replace the underlying concrete class with any class that provides the Queue interface, without having to change the code too much.

基本更改是将fifo的类型更改为Queue,并使用remove()代替removeFirst(),后者不适用于Queue界面.

The basic changes are to change the type of fifo to a Queue and to use remove() instead of removeFirst(), the latter being unavailable for the Queue interface.

调用isEmpty()仍然可以,因为它属于Collection接口的接口,而Queue是派生的.

Calling isEmpty() is still okay since that belongs to the Collection interface of which Queue is a derivative.

这篇关于Java中的FIFO类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆