Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

A very simple & quick question on Java libraries: is there a ready-made class that implements a Queue with a fixed maximum size - i.e. it always allows addition of elements, but it will silently remove head elements to accomodate space for newly added elements.

Of course, it's trivial to implement it manually:

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;

    }

}

As far as I see, there's no standard implementation in Java stdlibs, but may be there's one in Apache Commons or something like that?

1 Answer

0 votes
by (46k points)

Guava now has an EvictingQueuea non-blocking queue which automatically evicts elements from the head of the queue when attempting to add new elements onto the queue and it is full.

import java.util.Queue;

import com.google.common.collect.EvictingQueue;

Queue<Integer> fifo = EvictingQueue.create(2); 

fifo.add(1); 

fifo.add(2); 

fifo.add(3); 

System.out.println(fifo); 

// Observe the result: 

// [2, 3]

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Nov 13, 2019 in Java by Nigam (4k points)
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...