Queue Implementation in JAVA

This is my Java implementation of the Queue data structure. It exhibits the first in first out property, which is useful in applications such as breadth first traversal and other Arrays algorithms. This implementation leverages the Java standard library Arrays data structure as a buffer to hold incoming elements. Due to the fixed size of the Java Arrays after instantiation, I have also implemented the resize method to double the threshold of the original buffer once it has reached its limit. The circular nature of this Queue implementation enforces that all slots are filled before the buffer is resized. The methods this Queue supports are peek, add, and remove.

public static class Queue<T> {
    T[] buffer;
    int head;
    int tail;
    int threshold;

    public Queue(int k) {
        threshold = k;
        head = -1;
        tail = -1;
        buffer = (T[]) new Object[threshold];
    }

    public Queue() {
        this(11);
    }

    public T peek() {
        if (head == -1) return null;
        return buffer[head];
    }

    public void add(T d) {
        tail = (tail + 1) % threshold;
        if (tail == head) resize();

        buffer[tail] = d;

        if(head == -1) head = 0;
    }

    public T remove() {
        if (head == -1) return null;
        T d = buffer[head];

        if (head == tail) {
            head = -1;
            tail = -1;
        }
        else {
            head = (head + 1) % threshold;
        }

        return d;
    }

    private void resize() {
        T[] temp = buffer;
        buffer = (T[]) new Object[threshold << 1];

        for (int i = 0; i < threshold; i++) {
            int j = (head + i) % threshold;
            buffer[i] = temp[j];
        }

        head = 0;
        tail = threshold;
        threshold = threshold << 1;
    }
}

This article is my 11th oldest. It is 239 words long, and it’s got 0 comments for now.