Java 集合只保留 n 个最后插入的成员

标签 java collections

如标题所述,我正在寻找一个 java 集合,只保留插入到集合中的最后 N 个对象。这个FIFO集合不需要实现随机访问,也不需要支持改变N。

我能找到的所有集合要么是阻塞的(LinkedBlockingQueue),要么是无限大小的(ArrayDeque)。我找到了 org.eclipse.jetty.util.ArrayQueue,但正如您可能猜到的那样,这对我的项目带来了相当不必要的依赖,而且非常复杂,因为它支持更改 N,所以它不是我需要的。

您知道是否有一种方法可以使用非常常见的 Java 库,还是我必须自己编写它?

最佳答案

查看 Apache Commons CircularFifoBuffer

CircularFifoBuffer is a first in first out buffer with a fixed size that replaces its oldest element if full.

The removal order of a CircularFifoBuffer is based on the insertion order; elements are removed in the same order in which they were added. The iteration order is the same as the removal order.

关于Java 集合只保留 n 个最后插入的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11850631/

相关文章:

java - 如果同一平台上有两个或多个不同的 jre 实现,会发生什么情况?

java - h :commandButton works from the second click

grails - 如何在 Grails 中搜索其集合中包含另一个元素的元素?

java - 有没有更好的方法从 Map 中检索值

java - 为什么要在 EDT 线程外调用 SwingUtils.invokeAndWait() 方法?

java - 如何从 .getProperty ('style"中获取值

java - 指定 Java 类路径

VB.net:我的线程安全列表解决方案真的安全吗?

arrays - 集合/数组包含方法

collections - DocumentDB 对集合的权限