Size-limited queue that holds last N elements in Java

A very simple & quick question on Java libraries: is there a ready-made class that implements a Queuewith a fixed maximum size - i.e. it always allows addition of elements, but it will silently remove head elements to accomodate space for newly added elements.

Of course, it's trivial to implement it manually:

import java.util.LinkedList; public class LimitedQueue<E> extends LinkedList<E> { private int limit; public LimitedQueue(int limit) { this.limit = limit; } @Override public boolean add(E o) { super.add(o); while (size() > limit) { super.remove(); } return true; } }

As far as I see, there's no standard implementation in Java stdlibs, but may be there's one in Apache Commons or something like that?





47 down vote accepted
+50

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.

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

Update: updated answer following release of commons collections version 4


你可能感兴趣的:(element)