Size-limited queue that holds last N elements in Java

后端 未结 8 1543
灰色年华
灰色年华 2020-11-22 13:13

A very simple & quick question on Java libraries: is there a ready-made class that implements a Queue with a fixed maximum size - i.e. it always allows addi

8条回答
  •  暖寄归人
    2020-11-22 13:24

    Apache commons collections 4 has a CircularFifoQueue<> which is what you are looking for. Quoting the javadoc:

    CircularFifoQueue is a first-in first-out queue with a fixed size that replaces its oldest element if full.

        import java.util.Queue;
        import org.apache.commons.collections4.queue.CircularFifoQueue;
    
        Queue fifo = new CircularFifoQueue(2);
        fifo.add(1);
        fifo.add(2);
        fifo.add(3);
        System.out.println(fifo);
    
        // Observe the result: 
        // [2, 3]
    

    If you are using an older version of the Apache commons collections (3.x), you can use the CircularFifoBuffer which is basically the same thing without generics.

    Update: updated answer following release of commons collections version 4 that supports generics.

提交回复
热议问题