I need a queue like CircularFifoQueue in Apache Commons but with the ability to iterate elements backward. I.e. I need to insert elements in a fixed size queue with auto remove of old elements. But I need to iterate elements starting from the youngest element. Is there something available in Java?
1
votes
Have you looked through the classes that implement the Java Deque interface (docs.oracle.com/javase/7/docs/api/java/util/Deque.html)? Any of the these classes may work for you as they provide a descendingIterator() method to, well, iterate in reverse order.
– Michael Peacock
But any Deque has to have descendingIterator(). Still I didn't find Deque with auto-remove of old elements.
– Oleksandr
1 Answers
1
votes
I can use something like this (need also rewrite other insert methods like push, pushLast...) but would like to hear other available solutions (if they exist).
public class ConcurrentFixedSizeLinkedDeque<T> extends ConcurrentLinkedDeque<T> {
private int sizeLimit = Integer.MAX_VALUE;
public ConcurrentFixedSizeLinkedDeque() {
}
public ConcurrentFixedSizeLinkedDeque(Collection<? extends T> c) {
super(c);
}
public ConcurrentFixedSizeLinkedDeque(int sizeLimit) {
if(sizeLimit<0) sizeLimit=0;
this.sizeLimit = sizeLimit;
}
public ConcurrentFixedSizeLinkedDeque(Collection<? extends T> c, int sizeLimit) {
super(c);
if(sizeLimit<0) sizeLimit=0;
this.sizeLimit = sizeLimit;
}
public int getSizeLimit() {
return sizeLimit;
}
public void setSizeLimit(int sizeLimit) {
this.sizeLimit = sizeLimit;
}
@Override
public void addFirst(T e){
while(size()>=this.sizeLimit){
pollLast();
}
super.addFirst(e);
}
@Override
public void addLast(T e){
while(size()>=this.sizeLimit){
pollFirst();
}
super.addLast(e);
}
}