Reputation: 1693
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?
Upvotes: 1
Views: 8893
Reputation: 21434
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.
Upvotes: 4
Reputation: 13384
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 ..
Upvotes: 4