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.
Java
import java.util.LinkedList;
import java.util.Queue;
class GFG {
public static class SizeLimitedQueue<E>
extends LinkedList<E> {
private int SizeLimitOfQueue;
public SizeLimitedQueue( int SizeLimitOfQueue)
{
this .SizeLimitOfQueue = SizeLimitOfQueue;
}
@Override
public boolean add(E o)
{
while ( this .size() == SizeLimitOfQueue) {
super .remove();
}
super .add(o);
return true ;
}
}
public static void main(String[] args)
{
Queue<Integer> q = new SizeLimitedQueue<>( 3 );
for ( int i = 0 ; i < 5 ; i++)
q.add(i);
int size = q.size();
System.out.println( "Size of queue-" + size);
System.out.println( "Elements of queue " + q);
int removedele = q.remove();
System.out.println( "Removed element-" + removedele);
for ( int i = 5 ; i < 7 ; i++)
q.add(i);
System.out.println( "Elements of queue " + q);
int head = q.peek();
System.out.println( "Head of queue-" + head);
size = q.size();
System.out.println( "Size of queue-" + size);
}
}
|
Output
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
Related Articles:
Last Updated :
23 Nov, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...