java - 有限制的集合,如果达到限制,可以在添加新项目之前删除旧项目

标签 java collections

谁知道有限制的集合以及在达到限制时能够在添加新项目之前删除旧项目的能力?

旧条目是放置在开头的条目。

最佳答案

您应该使用 Apache Commons Collections 中的 org.apache.commons.collections4.queue.CircularFifoQueue及其构造函数CircularFifoQueue(final int size)

CircularFifoQueue is a first-in first-out queue with a fixed size that replaces its oldest element if full. The removal order of a CircularFifoQueue 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.

示例:

class Test {
    public static void main(String[] args) {
        Queue<Integer> numbers = new CircularFifoQueue<>(2);
        for (int i = 0; i < 4; i++) {
            numbers.add(i);
            System.out.println("Iteration#" + i + " : " + numbers);
        }
    }
}

// Output:
// Iteration#0 : [0]
// Iteration#1 : [0, 1]
// Iteration#2 : [1, 2]
// Iteration#3 : [2, 3]

关于java - 有限制的集合,如果达到限制,可以在添加新项目之前删除旧项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39077168/

相关文章:

java - 遵循 LibGdx 中的路径

java - 修复打开文件过多异常(我正在使用 try-catch-finally)

java - 对列表进行排序,同时将一些元素始终放在顶部

java - 使用 spring 表达式语言 (SpEL) 更新集合中的属性

java - Bean类与集合: which one should i prefer to hold data

c# - 添加解释为数字和短整型的 byte[]

java - 如何通过 wicket ajax 行为捕获来自 &lt;input type ="date"> 的事件?

java - 为什么我的通用实现不起作用? (扩展Comparable<? super T>>)

java - 如何使用 Spring Data(MongoDB) 映射通用集合?

sorting - Smalltalk 集合