I was reading a queue implementation that I stumbled upon in Github and was having difficulty understanding why certain behaviors were used. (The link to the repository could be found here )
public ArrayQueue(int capacity) {
// ArrayQueue maximum size is data.length - 1.
data = new Object[capacity + 1];
front = 0;
rear = 0;
}
public void offer(T elem) {
if (isFull()) {
throw new RuntimeException("Queue is full");
}
data[rear++] = elem;
rear = adjustIndex(rear, data.length);
}
public T poll() {
if (isEmpty()) {
throw new RuntimeException("Queue is empty");
}
front = adjustIndex(front, data.length);
return (T) data[front++];
}
public boolean isFull() {
return (front + data.length - rear) % data.length == 1;
}
Thank you
ArrayQueue maximum size is data.length - 1. The place of the variable rear is always in front of the variable front logistically if regard the data array as circular. so the number of states of the combination of rear and front is the length of the data array. And one of the total states is used to be the judge if the queue is empty or full.
read
is adjusted after because rear
is the place where the new element is supposed to be added. After the element is added, it is incremented. And front
is the index where the element is supposed to be popped out, because it alread has the element.data.length - 1
so front - rear
has to equal 1
if the queue is supposed to be full.I hope this answers your question. Feel free to ask questions in the comments.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.