Home >Java >javaTutorial >How Can I Implement a Size-Limited Queue in Java Easily?
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 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<Integer> 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.
The above is the detailed content of How Can I Implement a Size-Limited Queue in Java Easily?. For more information, please follow other related articles on the PHP Chinese website!