Java中的环形缓冲区 [英] Ring Buffer in Java

查看:396
本文介绍了Java中的环形缓冲区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个流时间序列,我希望保留其中的最后4个元素,这意味着我希望能够弹出第一个元素并将其添加到末尾.基本上,我需要的是 环形缓冲区 .

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.

哪个Java Collection最适合此?向量?

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将为您执行以下操作:

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

  • CircularFifoBuffer是具有固定值的先进先出缓冲区 大小,如果已满则替换其最早的元素.
  • CircularFifoBuffer的删除顺序基于插入 命令;元素的删除顺序与原先的删除顺序相同 添加.迭代顺序与删除顺序相同.
  • add(Object),BoundedFifoBuffer.remove()和 BoundedFifoBuffer.get()操作均在恒定时间内执行. 所有其他操作都在线性时间内或更差的时间执行.
  • 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.

注意:使用当前的常用收藏夹(4. *) ,则必须使用Queue.像这样:

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

Queue buf = new CircularFifoQueue(4);

这篇关于Java中的环形缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆