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; } }</e></e>
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]</integer>
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

Atom editor mac version download
The most popular open source editor

SublimeText3 English version
Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.