How to Implement a Size-Limited Queue in Java
In Java, a standard implementation for a queue with a fixed maximum size does not exist. However, implementing it manually is straightforward:
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; } }
Apache Commons Collections Solution
Alternatively, Apache Commons Collections 4 provides a CircularFifoQueue class that meets the requirements:
import java.util.Queue; import org.apache.commons.collections4.queue.CircularFifoQueue; Queue<Integer> fifo = new CircularFifoQueue<>(2); fifo.add(1); fifo.add(2); fifo.add(3); System.out.println(fifo); // [2, 3]
For Apache Commons Collections 3.x, use CircularFifoBuffer.
The above is the detailed content of How to Implement a Size-Limited Queue in Java?. For more information, please follow other related articles on the PHP Chinese website!