I am trying to implement a Ring (circular queue) of Chars in Java and I'm having a difficult time thinking through how to detect if the buffer isEmpty without using the .size() method on the array.
Because if the Ring Buffer is full read pointer == write pointer
but also if the Ring Buffer is empty, read pointer == write pointer
so I'm not sure how to check for isEmpty() correctly. I know that I can do it with .size() but I'm trying to figure out if it's possible to implement it without.
I know that I will need to waste a space at the end of the array but I'm not sure how to check it. Would the check be as simple as if (head != (tail - 1))
?
Also, I am trying to write the flush()
method and I think I can do so with a for each loop looking like this:
for(char c : items){
c = (Character) null;
}
But eclipse yells at me for null pointer access requiring auto boxing and unboxing.
Any help would be very much appreciated. The full class is below for reference:
public class RingBuffer {
private char[] items;
private int front;
private int rear;
private int last;
public RingBuffer(int capacity){
items = new char[capacity +1];
front = 0;
rear = 0;
last = capacity;
}
public void flush(){
for(char c : items){
c = (Character) null;
}
}
public boolean isEmpty(){
return false;
}
}