I'm implementing a generic circular array and I would like to make it parcelable. To be able to have the circular array generic, I need to pass the type in the constructor. However, implementing Parcelable
requires a constructor that only passes a Parcel
. The two requirements are conflicting and I can't think of a way around this.
This is my attempt, which would fail on the CircularArray(Parcel in)
constructor as it's missing the type.
import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;
import java.lang.reflect.Array;
import java.util.Arrays;
/**
* Created by dav on 08/06/15.
*/
public class CircularArray<T> implements Parcelable {
public static final int DEFAULT_SIZE = 10;
protected Class<T> c;
protected final T[] mQueue;
protected int curr = 0;
protected int n;
public CircularArray(Class<T> c, int n) {
this.n = n;
this.c = c;
mQueue = (T[]) new Object[n];
curr = 0;
}
public CircularArray(Class<T> c) {
this(c, DEFAULT_SIZE);
}
public CircularArray(Parcel in) {
mQueue = (T[]) in.readArray(CircularArray.class.getClassLoader());
n = mQueue.length;
}
public void fill(T value) {
Arrays.fill(mQueue, value);
}
public void add(T item) {
mQueue[curr] = item;
curr = (curr + 1) % n;
}
/**
* Sort the elements in the right order0 and return them
* @return the queue in the correct order.
*/
public T[] getAll() {
int last = curr+1% n;
int counter = 0;
Log.i("Circular", "Component is " + mQueue.getClass().getComponentType());
T[] out = (T[]) Array.newInstance(c, n); //new Object[n];
for (int i = curr; i< n; i++) {
out[counter++] = mQueue[i];
}
for (int i = 0; i<curr; i++) {
out[counter++] = mQueue[i];
}
return out;
}
public T getOne() {
return mQueue[curr];
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeArray(mQueue);
}
public static final Parcelable.Creator<CircularArray> CREATOR
= new Parcelable.Creator<CircularArray>() {
public CircularArray createFromParcel(Parcel in) {
return new CircularArray(in);
}
public CircularArray[] newArray(int size) {
return new CircularArray[size];
}
};
}