RingBuffer implementation

The ring buffer can be implemented using a simple array of items. We need to keep track of two indexes between which useful data is actually stored.

The enqueue operation moves the last index one step to the right (or wrap around). The dequeue operation moves the first index one step to the right (or wrap around).

public class RingBuffer {
    private final Item buffer[];
    private int size, maxSize, first, last;

    public RingBuffer(final int maxSize) {
        this.maxSize = maxSize;
        buffer = (Item[]) new Object[maxSize];
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public boolean isFull() {
        return size == maxSize;
    }

    public void enqueue(final Item item) {
        if (isFull()) {
            throw new...;
        }

        buffer[last] = item;
        last++;
        if (last == maxSize) {
            last = 0;
        }
        size++;
    }

    public Item dequeue() {
        if (isEmpty()) {
            throw new...;
        }

        Item result = buffer[first];
        first++;
        if (first == maxSize) {
            first = 0;
        }
        size--;
        return result;
    }
}
Advertisements