Size-limited queue that holds last N elements in Java

后端 未结 8 1583
灰色年华
灰色年华 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:33

    Guava now has an EvictingQueue, a non-blocking queue which automatically evicts elements from the head of the queue when attempting to add new elements onto the queue and it is full.

    import java.util.Queue;
    import com.google.common.collect.EvictingQueue;
    
    Queue fifo = EvictingQueue.create(2); 
    fifo.add(1); 
    fifo.add(2); 
    fifo.add(3); 
    System.out.println(fifo); 
    
    // Observe the result: 
    // [2, 3]
    

提交回复
热议问题