Home > Java > javaTutorial > How to Implement a Fixed-Size Queue in Java?

How to Implement a Fixed-Size Queue in Java?

Susan Sarandon
Release: 2024-12-08 09:54:11
Original
300 people have browsed it

How to Implement a Fixed-Size Queue in Java?

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]
Copy after login

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]
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template