Question
Is there a pre-existing class in Java that implements a fixed-size queue preserving the last N elements while removing the oldest?
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;
}
}
Answer
Java does not provide a built-in size-limited queue. However, you can use a custom implementation or libraries like Apache Commons Collections which can provide similar functionality. Below is a detailed explanation of how to implement a size-limited queue in Java.
import org.apache.commons.collections4.queue.CircularFifoQueue;
// Example of using CircularFifoQueue from Apache Commons Collections
CircularFifoQueue<Integer> queue = new CircularFifoQueue<>(3);
queue.add(1);
queue.add(2);
queue.add(3);
queue.add(4); // This will remove 1 and keep 2, 3, 4
System.out.println(queue); // Output: [2, 3, 4]
Causes
- The Java Collections Framework does not include a specific implementation of a bounded queue that automatically manages size.
- Most queue implementations (like ArrayDeque or LinkedList) allow unbounded sizes.
Solutions
- Implement a custom class extending LinkedList, as shown in the provided code snippet.
- Utilize third-party libraries like Apache Commons Collections, which provides a CircularFifoQueue that can store a limited number of elements.
Common Mistakes
Mistake: Forgetting to handle synchronization issues in multi-threaded environments.
Solution: Use synchronized methods or consider using ConcurrentLinkedQueue with size management.
Mistake: Trying to use arrays for fixed-size queues without proper management.
Solution: Always prefer dynamic data structures like LinkedList or use the specialized classes from libraries.
Helpers
- Java Fixed Size Queue
- Java Limit Queue Implementation
- Size-limited Queue Java Example
- Java Collections Framework
- Apache Commons Circular Queue