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

How to Implement a Size-Limited Queue in Java?

Barbara Streisand
Release: 2024-12-01 18:03:11
Original
222 people have browsed it

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;
    }
}
Copy after login

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]
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template