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; CircularFifoQueuequeue = 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.
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