ArrayCharQueue.java
package ch.hslu.exercises.sw02.ex4;
import java.nio.BufferOverflowException;
import java.util.Arrays;
import java.util.NoSuchElementException;
public final class ArrayCharQueue implements CharQueue {
private final char[] array = new char[8];
private int headIndex = array.length - 1;
private int tailIndex = array.length - 1;
private int size = 0;
@Override
public void offer(final char element) {
if (isFull()) {
throw new BufferOverflowException();
}
array[tailIndex] = element;
tailIndex = handleRingBufferBehaviour(tailIndex);
size++;
}
@Override
public char poll() {
if (isEmpty()) {
throw new NoSuchElementException();
}
char out = array[headIndex];
headIndex = handleRingBufferBehaviour(headIndex);
size--;
return out;
}
@Override
public int size() {
return size;
}
private int handleRingBufferBehaviour(final int index) {
int nextIndex;
if (index == 0) {
nextIndex = array.length - 1;
} else {
nextIndex = index - 1;
}
return nextIndex;
}
private boolean isEmpty() {
return size == 0;
}
private boolean isFull() {
return size == array.length;
}
@Override
public String toString() {
return "ArrayCharQueue{"
+ "array=" + Arrays.toString(array)
+ ", headIndex=" + headIndex
+ ", tailIndex=" + tailIndex
+ ", size=" + size
+ '}';
}
}