如何实现先进先出的队列满了自动弹出?

How to implement a queue where the first-in item is automatically popped out when full?

我正在跟踪颜色列表。我只需要担心添加到此列表中的最后两种颜色。所以这个队列应该是固定大小的(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是否有针对此类操作的内置集合?还是需要自己搭建?

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

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.