gpt4 book ai didi

java - 如何实现队列满了自动弹出先入项?

转载 作者:行者123 更新时间:2023-12-01 11:55:17 27 4
gpt4 key购买 nike

我正在跟踪颜色列表。我只需要担心添加到此列表中的最后两种颜色。所以这个队列应该是固定大小(2)。

    queue.add(color1);
queue.add(color2);
queue.add(color3); //adding color3 should automatically remove color1 from the queue.
//So the queue should now only contain 'color2' and 'color3'

Java 是否有用于此类操作的内置 Collection?还是我需要自己构建它?

最佳答案

我想您可能正在寻找 CircularFifoQueue 来自 Apache Commons 4.x,它具有固定大小并默默地删除元素以为新元素腾出空间。这是来自文档:

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.

关于java - 如何实现队列满了自动弹出先入项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28502383/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com