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

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

Patricia Arquette
Patricia ArquetteOriginal
2024-11-29 11:58:10763browse

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<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!

Statement:
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