谁知道有限制的集合以及在达到限制时能够在添加新项目之前删除旧项目的能力?
旧条目是放置在开头的条目。
最佳答案
您应该使用 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/