Java - 环形缓冲区 [英] Java - Ring Buffer

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

问题描述

我有一个流媒体时间序列,我有兴趣保留最后4个元素,这意味着我希望能够弹出第一个,然后添加到最后。哪个Java Collection最适合这个?向量?

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. Which Java Collection is the best for this? Vector ?

推荐答案

考虑 CircularFifoBuffer Common.Collections 。与队列不同,您没有保持底层集合的有限大小,并在达到限制时将其包装。

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 becaue it doens't allow nulls.

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

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