我需要一个数据结构,可以有效地缓冲特定数量的元素,在先进先出的顺序。
正如在this question中提到的,Apache Commons有一个CircularFifoBuffer,但遗憾的是它没有泛化。Some forks存在,但我不确定它们的维护状态。
由于Guava是满足我的收藏需求的首选图书馆,我想知道:在Guava中有没有好的替代方案?如果没有,我是否应该基于Apache Commons的CircularFifoBuffer在我的项目中实现它?
发布于 2013-05-06 15:41:58
启动Guava15.0-您可以使用EvictingQueue
发布于 2013-01-09 18:28:44
我在Guava中看不到类似的东西,但是围绕ArrayDeque
构建的ForwardingQueue
如何,您可以检查add()
、offer()
等上的容量,如果旧条目已经满了,则检查remove()
旧条目。
发布于 2013-01-09 19:44:30
如果你想在泛型中使用Apache (它包含了可用的CircularFifoBuffer<E>
类),Commons-Collections with Generics (maven link)是最好的选择。
另一方面,正如@FrankPavageau所说,你可以使用你自己的ForwardingQueue
实现。一种简单的方法(有进一步优化的地方)应该是这样的:
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);
}
}
用法:
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]
https://stackoverflow.com/questions/14232548
复制相似问题