I have an assignment to implement a generic circular buffer.
Everything is fine, I only need to do a sort
method however I cannot think of a solution to make it generic.
Could you please give me a hint?
Thank you!
public class CircularBuffer<T> {
public T[] elements = null;
private int capacity = 0;
private int dataStart = 0;
private int dataEnd = 0;
@SuppressWarnings("unchecked")
public CircularBuffer(int capacity) {
this.capacity = capacity;
this.elements = (T[]) new Object[capacity];
}
public boolean isEmpty() {
return dataStart == dataEnd;
}
public boolean isFull() {
if (dataStart == 0) {
return dataEnd == capacity - 1 ;
}
return dataStart - dataEnd == 1;
}
public int size() {
return dataEnd - dataStart;
}
public void put(T t) {
if (isFull()) {
throw new RuntimeException("Buffer is full");
}
if (dataEnd < capacity) {
elements[dataEnd] = t;
dataEnd++;
}
}
public T get() {
if (isEmpty()) {
throw new RuntimeException("Buffer is empty");
}
return elements[dataStart++];
}
public Object[] toObjectArray() {
Object[] newArray = new Object[size()];
for (int i = dataStart; i < dataEnd; i++) {
newArray[i] = elements[i];
}
return newArray;
}
@SuppressWarnings("unchecked")
public <Q> Q[] toArray(Q[] a) {
if (a.length < size())
return (Q[]) Arrays.copyOf(elements, size(), a.getClass());
System.arraycopy(elements, 0, a, 0, size());
return a;
}
public List<T> asList(List<T> a) {
List<T> list = new ArrayList<>(size());
for (int i = dataStart; i < dataEnd; i++) {
list.add(elements[i]);
}
return list;
}
public void addAll(List<? extends T> toAdd) {
if (toAdd.size() > capacity - size()) {
throw new RuntimeException("Not enough space to add all elements");
}
else {
for (int i = 0; i < toAdd.size(); i++) {
elements[dataEnd] = toAdd.get(i);
dataEnd++;
}
}
}
public void sort(Comparator<? super T> comparator) {
// TODO
}
}
The simplest option would be to get the contents out as a List
, sort it and replace the old contents from the now sorted list.
public void sort(Comparator<? super T> comparator) {
// Get them all out - not sure why you have a parameter to `asList`
List<T> all = asList(Collections.emptyList());
// Sort them.
Collections.<T>sort(all);
// Clear completely.
dataStart = dataEnd = 0;
addAll(all);
}
You will need to change the signature of your class to ensure T
is sortable.
public class CircularBuffer<T extends Comparable<T>> {