Commons-Collections with Generics (maven link) is the way to go if you want to use Apache Collections with generics (and it contains working CircularFifoBuffer<E>
class).
On the other hand, as @FrankPavageau says, you can use your own ForwardingQueue
implementatation. A naive approach (with place for further optimizations) would be something like this:
static class BoundedQueue<E> extends ForwardingQueue<E> {
private final Queue<E> delegate;
private final int capacity;
public BoundedQueue(final int capacity) {
this.delegate =
new ArrayDeque<E>(capacity); // specifying initial capacity is optional
this.capacity = capacity;
}
@Override
protected Queue<E> delegate() {
return delegate;
}
@Override
public boolean add(final E element) {
if (size() >= capacity) {
delegate.poll();
}
return delegate.add(element);
}
@Override
public boolean addAll(final Collection<? extends E> collection) {
return standardAddAll(collection);
}
@Override
public boolean offer(final E o) {
return standardOffer(o);
}
}
Usage:
final BoundedQueue<Integer> boundedQueue = new BoundedQueue<Integer>(3);
boundedQueue.add(1);
System.out.println(boundedQueue); // [1]
boundedQueue.add(2);
System.out.println(boundedQueue); // [1, 2]
boundedQueue.add(3);
System.out.println(boundedQueue); // [1, 2, 3]
boundedQueue.add(4);
System.out.println(boundedQueue); // [2, 3, 4]
boundedQueue.addAll(Arrays.asList(5, 6, 7, 8));
System.out.println(boundedQueue); // [6, 7, 8]
((Queue<Integer>) boundedQueue).offer(9);
System.out.println(boundedQueue); // [7, 8, 9]