"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Implement a Size-Limited Queue in Java Easily?

How Can I Implement a Size-Limited Queue in Java Easily?

Posted on 2025-02-27
Browse:924

How Can I Implement a Size-Limited Queue in Java Easily?

Ready-Made Implementation of Size-Limited Queue in Java

A Queue can be useful when working with limited resources, as it ensures that the oldest elements are removed when adding new elements. However, implementing this manually can be cumbersome.

Apache Commons Collections CircularFifoQueue

Apache Commons Collections 4 offers a convenient solution with its CircularFifoQueue. As per its documentation:

CircularFifoQueue is a first-in first-out queue with a fixed size that replaces its oldest element if full.

Using this class is straightforward:

import org.apache.commons.collections4.queue.CircularFifoQueue;

CircularFifoQueue queue = new CircularFifoQueue(2);
queue.add(1);
queue.add(2);
queue.add(3);
System.out.println(queue); // [2, 3]

Notice how the oldest element (1) is removed when adding 3 despite the queue's maximum size of 2.

For older versions of Apache Commons Collections (3.x), the CircularFifoBuffer can be used, which operates similarly but lacks generics.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3