Java 中保存最后 N 个元素的大小受限队列

2022-01-21 00:00:00 queue collections java

一个非常简单的 &关于 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 标准库中没有标准实现,但可能在 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 有一个 CircularFifoQueue<> 这就是你要找的.引用 javadoc:

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

CircularFifoQueue 是一个具有固定大小的先进先出队列,如果已满则替换其最旧的元素.

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]

如果您使用的是旧版本的 Apache 公共集合 (3.x),您可以使用 CircularFifoBuffer 基本上没有泛型是一样的.

If you are using an older version of the Apache commons collections (3.x), you can use the CircularFifoBuffer which is basically the same thing without generics.

更新:在支持泛型的公共集合版本 4 发布后更新了答案.

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

相关文章