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

How to Implement a Size-Limited Queue in Java?

Barbara Streisand
Barbara StreisandOriginal
2024-12-01 18:03:11241browse

How to Implement a Size-Limited Queue in Java?

How to Implement a Size-Limited Queue in Java

In Java, a standard implementation for a queue with a fixed maximum size does not exist. However, implementing it manually is straightforward:

import java.util.LinkedList;

public class LimitedQueue<E> extends LinkedList<E> {
    private int limit;

    public LimitedQueue(int limit) {
        this.limit = limit;
    }

    @Override
    public boolean add(E o) {
        super.add(o);
        while (size() > limit) {
            super.remove();
        }
        return true;
    }
}

Apache Commons Collections Solution

Alternatively, Apache Commons Collections 4 provides a CircularFifoQueue class that meets the requirements:

    import java.util.Queue;
    import org.apache.commons.collections4.queue.CircularFifoQueue;

    Queue<Integer> fifo = new CircularFifoQueue<>(2);
    fifo.add(1);
    fifo.add(2);
    fifo.add(3);
    System.out.println(fifo); // [2, 3]

For Apache Commons Collections 3.x, use CircularFifoBuffer.

The above is the detailed content of How to Implement a Size-Limited Queue in Java?. 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