How would you code an efficient Circular Buffer in Java or C#

Posted by Cheeso on Stack Overflow See other posts from Stack Overflow or by Cheeso
Published on 2009-02-26T11:02:23Z Indexed on 2010/05/22 21:30 UTC
Read the original article Hit count: 252

Filed under:
|
|

I want a simple class that implements a fixed-size circular buffer. It should be efficient, easy on the eyes, generically typed.

EDIT: It need not be MT-capable, for now. I can always add a lock later, it won't be high-concurrency in any case.

Methods should be: .Add and I guess .List, where I retrieve all the entries. On second thought, Retrieval I think should be done via an indexer. At any moment I will want to be able to retrieve any element in the buffer by index. But keep in mind that from one moment to the next Element[n] may be different, as the Circular buffer fills up and rolls over.

This isn't a stack, it's a circular buffer. Regarding "overflow": I would expect internally there would be an array holding the items, and over time the head and tail of the buffer will rotate around that fixed array. But that should be invisible from the user. There should be no externally-detectable "overflow" event or behavior.

This is not a school assignment - it is most commonly going to be used for a MRU cache or a fixed-size transaction or event log.

© Stack Overflow or respective owner

Related posts about c#

Related posts about java