Implementing a Size-Limited Queue in Java
Developers often encounter the need for a data structure that maintains a fixed size while continuously adding elements. In Java, implementing a size-limited queue is straightforward but requires manual coding. However, alternatives exist within external libraries.
Apache Commons Collections 4 introduces the CircularFifoQueue class, which aligns with the desired functionality:
"CircularFifoQueue is a first-in first-out queue with a fixed size that replaces its oldest element if full."
Example Usage with Generics:
import org.apache.commons.collections4.queue.CircularFifoQueue; // Create a queue with a limit of 2 elements CircularFifoQueue<Integer> fifo = new CircularFifoQueue<>(2); // Add elements fifo.add(1); fifo.add(2); // Add a third element (replaces oldest element, in this case 1) fifo.add(3); // Print the queue System.out.println(fifo); // Output: [2, 3]
Example Usage with Non-Generics (Apache Commons Collections 3):
import org.apache.commons.collections.buffer.CircularFifoBuffer; // Create a queue with a limit of 2 elements CircularFifoBuffer fifo = new CircularFifoBuffer(2); // Add elements fifo.add(1); fifo.add(2); // Add a third element (replaces oldest element, in this case 1) fifo.add(3); // Print the queue System.out.println(fifo); // Output: [2, 3]
Utilizing these ready-made classes simplifies the implementation of size-limited queues in Java while ensuring efficiency and preventing code duplication.
The above is the detailed content of How to Implement a Fixed-Size Queue in Java?. For more information, please follow other related articles on the PHP Chinese website!