Java
Queue
Data Structures
Programming
Algorithms

Size-limited queue that holds last N elements in Java

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

In Java, a Size-limited Queue, which holds the last N elements, is a useful data structure that provides a way to maintain a collection of elements with a fixed size. As new elements are added beyond the capacity, the oldest elements are automatically evicted, which is particularly useful in scenarios where only the most recent data is needed. This data structure can be akin to a 'sliding window' over a stream of incoming data.

Implementing a Size-limited Queue in Java

In Java, this can be efficiently implemented using the LinkedList or the ArrayDeque classes from the java.util package. Both provide operations that permit adding and removing elements in constant time O(1)O(1).

Example Implementation

Here's an example of how to implement a Size-limited Queue using a LinkedList.

java
1import java.util.LinkedList;
2
3public class SizeLimitedQueue<T> {
4    private final int maxSize;
5    private final LinkedList<T> queue;
6
7    public SizeLimitedQueue(int maxSize) {
8        this.maxSize = maxSize;
9        this.queue = new LinkedList<>();
10    }
11
12    public void add(T element) {
13        if (queue.size() >= maxSize) {
14            queue.poll(); // Remove the oldest element
15        }
16        queue.add(element);
17    }
18
19    public T remove() {
20        return queue.poll();
21    }
22
23    public T peek() {
24        return queue.peek();
25    }
26
27    public int size() {
28        return queue.size();
29    }
30
31    public boolean isEmpty() {
32        return queue.isEmpty();
33    }
34}

Explanation

  • Data Structure: We use LinkedList as the underlying data structure for the queue. This choice allows for efficient insertions and deletions.
  • Constructor: The constructor takes a single argument that specifies the maximum size of the queue.
  • Add method: This method adds a new element to the queue. If the current size of the queue is equal to the maximum allowed size, it removes the oldest element before adding the new one.
  • Remove method: Removes and returns the earliest added element, or null if the queue is empty.
  • Peek method: Retrieves, but does not remove, the head of this queue, or returns null if the queue is empty.
  • Size and Empty methods: These provide utility functions to check the current size and whether the queue is empty.

Key Considerations

  1. Data Loss: The queue's size limit means that the oldest data can be lost. Thus, it's not suitable for scenarios where complete data retention is required.
  2. Thread Safety: The current implementation is not thread-safe. For multithreading scenarios, consider wrapping the operations in synchronized blocks or using concurrent collections like BlockingQueue subclasses.
  3. Use Cases:
    • Stream Processing: Useful in event-driven architectures or monitoring systems where only the most recent set of events is important.
    • Caching: When coupled with an eviction policy, it could be useful for implementing simple caching mechanisms that automatically remove old data.
    • Rate-limiting and Sliding Window Algorithms: Can be used in algorithms that require maintaining a subset of the latest entries.

Performance and Complexity

OperationTime Complexity
AddO(1)O(1) (average case)
RemoveO(1)O(1)
PeekO(1)O(1)
Size and isEmptyO(1)O(1)

Conclusion

The Size-limited Queue is a powerful tool in Java for controlling memory usage by maintaining a fixed-size collection of the most recent data. Implementing this using traditional collections like LinkedList or ArrayDeque allows for lean and efficient operations. However, developers should be mindful of the implications regarding data loss and consider thread safety when using this structure in concurrent environments.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.