1

How can we achieve Circular buffer implementation in Android?

Is there a way we can re-use a pre-defined method if exists? or do we have support for C standard libraries in Android?

Dan Hulme
  • 14,779
  • 3
  • 46
  • 95
Anvesh Yalamarthy
  • 1,625
  • 20
  • 36
  • 1
    did u read this ? http://stackoverflow.com/questions/590069/how-would-you-code-an-efficient-circular-buffer-in-java-or-c-sharp – Quick learner Jun 03 '15 at 06:07

2 Answers2

4

In Android development first preference is to use Java rather than C for implementing these things. Ofcourse you can do that in C (using JNI) but that requires certain overheads i.e. you need to implement your own garbage collection logic along with the code of circular buffer whereas in Java this can be achieved automatically. . See below class if it works for your case..

import java.nio.BufferOverflowException;
import java.nio.BufferUnderflowException;

public class CustomCircularBuffer<T> {

  private T[] buffer;

  private int tail;

  private int head;


  public CustomCircularBuffer(int n) {
    buffer = (T[]) new Object[n];
    tail = 0;
    head = 0;
  }

  public void add(T toAdd) {
    if (head != (tail - 1)) {
        buffer[head++] = toAdd;
    } else {
        throw new BufferOverflowException();
    }
    head = head % buffer.length;
  }

  public T get() {
    T t = null;
    int adjTail = tail > head ? tail - buffer.length : tail;
    if (adjTail < head) {
        t = (T) buffer[tail++];
        tail = tail % buffer.length;
    } else {
        throw new BufferUnderflowException();
    }
    return t;
  }

  public String toString() {
    return "CustomCircularBuffer(size=" + buffer.length + ", head=" + head + ", tail=" + tail + ")";
  }
}

Here are some other useful links which can give necessary explanations ..

Example

Another Example

In Depth Article

Amit
  • 13,134
  • 17
  • 77
  • 148
4

I just realized that ArrayDeque would be a good implementation for this.

There is also CircularArray from Android support.

CircularArray is a generic circular array data structure that provides O(1) random read, O(1) prepend and O(1) append. The CircularArray automatically grows its capacity when number of added items is over its capacity.

I can't tell its performance, but from a quick glance at the Javadocs, it seems to be designed with efficiency in mind. Not so sure anymore.

Hendy Irawan
  • 20,498
  • 11
  • 103
  • 114
  • 2
    Thanks for the information. On other note, you guys should be aware that certain CircularBuffer implementations set the capacity of the array to be static while others does so dynamic. Android's CircularArray and Java's ArrayDeque does so dynamically, which to some of us will requires custom implementation for a static capacity – Oz Shabat Nov 02 '19 at 10:55
  • @OzShabat do you happen to have a static-capacity ArrayDeque implemented? – dizcza Nov 01 '22 at 15:41
  • Nope, sorry. It's been long since I dealt with this – Oz Shabat Nov 01 '22 at 23:48