java 环形缓存,Java中的环形缓冲区

I have a streaming time series, of which I am interested in keeping the last 4 elements, which means I want to be able to pop the first, and add to the end. Essentially what I need is a ring buffer.

Which Java Collection is the best for this? Vector?

解决方案

Consider CircularFifoBuffer from Apache Common.Collections. Unlike Queue you don't have to maintain the limited size of underlying collection and wrap it once you hit the limit.

Buffer buf = new CircularFifoBuffer(4);

buf.add("A");

buf.add("B");

buf.add("C");

buf.add("D"); //ABCD

buf.add("E"); //BCDE

CircularFifoBuffer will do this for you because of the following properties:

CircularFifoBuffer is a first in first out buffer with a fixed

size that replaces its oldest element if full.

The removal order of a CircularFifoBuffer is based on the insertion

order; elements are removed in the same order in which they were

added. The iteration order is the same as the removal order.

The add(Object), BoundedFifoBuffer.remove() and

BoundedFifoBuffer.get() operations all perform in constant time.

All other operations perform in linear time or worse.

However you should consider it's limitations as well - for example, you can't add missing timeseries to this collection because it doens't allow nulls.

NOTE: When using current Common Collections (4.*), you have to use Queue. Like this:

Queue buf = new CircularFifoQueue(4);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值