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 个元素的大小受限队列
基础教程推荐
- 存储 20 位数字的数据类型 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
