How to implement size-limited Queue that holds last N elements in Java?
What is Size Limited Queue?
Size limited queue is the same as a normal queue but it has the special property that at any time queue can store at max N element, if we try to push more than N elements in the queue then accordingly the elements added at the starting will be removed from the queue means size will remain to fix i.e. N.
If you want to know more about queues refer to this article.
How to implement size limited queue in Java?
We can extend the LinkedList class that is available in Java and apply the necessary modifications to that class to create a size-limited queue in Java. I’ve modified the technique that adds elements to the queue in the code shown below.
Approach: Implement the idea below to solve the problem:
- Initialize the fixed size of the Queue and keep on adding elements in Queue unless its size becomes exactly equal to the fixed size.
- Override the add() method of the LinkedList class to incorporate the size restriction.
- If the Queue size gets equal to the fixed size remove the first element of the queue and then add a new one.
Below is the implementation of the above approach.
Size of queue-3 Elements of queue [2, 3, 4] Removed element-2 Elements of queue [4, 5, 6] Head of queue-4 Size of queue-3