Size-limited queue that holds last N elements in Java(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 标准库中没有标准实现,但可能在 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.
这篇关于Java 中保存最后 N 个元素的大小受限队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 中保存最后 N 个元素的大小受限队列


- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01