容纳Java中最后N个元素的大小有限队列 [英] Size-limited queue that holds last N elements in Java

查看:664
本文介绍了容纳Java中最后N个元素的大小有限队列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个很简单的&关于Java库的快速问题:是否有一个现成的类实现了一个固定最大大小的 Queue - 即它总是允许添加元素,但它会静默地删除头

A very simple & quick question on Java libraries: is there a ready-made class that implements a Queue with a fixed maximum size - i.e. it always allows addition of elements, but it will silently remove head elements to accomodate space for newly added elements.

当然,手动实现它是非常简单的:

Of course, it's trivial to implement it manually:

import java.util.LinkedList;

public class LimitedQueue<E> extends LinkedList<E> {
    private int limit;

    public LimitedQueue(int limit) {
        this.limit = limit;
    }

    @Override
    public boolean add(E o) {
        super.add(o);
        while (size() > limit) { super.remove(); }
        return true;
    }
}

据我所知, Java的stdlibs,但可能有一个在Apache Commons或类似的东西?

As far as I see, there's no standard implementation in Java stdlibs, but may be there's one in Apache Commons or something like that?

推荐答案

Apache commons collections 4有一个< =http://commons.apache.org/proper/commons-collections/javadocs/api-release/org/apache/commons/collections4/queue/CircularFifoQueue.html> CircularFifoQueue<> 这就是你正在找。引用javadoc:

Apache commons collections 4 has a CircularFifoQueue<> which is what you are looking for. Quoting the javadoc:


CircularFifoQueue是一个先进先出队列,具有固定大小, p>

CircularFifoQueue is a first-in first-out queue with a fixed size that replaces its oldest element if full.



    import java.util.Queue;
    import org.apache.commons.collections4.queue.CircularFifoQueue;

    Queue<Integer> fifo = new CircularFifoQueue<Integer>(2);
    fifo.add(1);
    fifo.add(2);
    fifo.add(3);
    System.out.println(fifo);

    // Observe the result: 
    // [2, 3]


$ b b

如果您使用的是较早版本的Apache commons集合(3.x),则可以使用 CircularFifoBuffer 基本上没有泛型。

更新 :在发布支持泛型的公共集合版本4之后的更新回答。

Update: updated answer following release of commons collections version 4 that supports generics.

这篇关于容纳Java中最后N个元素的大小有限队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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