'How to copy a circular queue to a larger array in Java?

I'm trying to copy a circular queue to a larger array in Java. Obviously if the array is not circular (i.e, [1, 2, 3, 4] where 1 is the front and 4 is the back) I can use the arraycopy method.

However how would I copy the elements to a larger array preserving the order. For example, if the array was [1, 2, 3, 4] but 4 is the front and 3 is the back, when copied to a larger array with twice the capacity, it should result in [4, 1, 2, 3, _, _, _, _].

public void add(int s) {
        if (size >= capacity) {
            int[] bigger = new int[capacity * 2];
            if (front <= back) {
                System.arraycopy(queue, front, bigger, 0, capacity); #error here
            } else {
                System.arraycopy(queue, front, bigger, 0, capacity-front);
                System.arraycopy(queue, 0, bigger, capacity-front, front);
            }
            front = 0;
            back = queue.length;
            queue = bigger;
            capacity *= 2;
        }
        
        queue[back] = s;
        back = (back + 1) % capacity;
        size++;
    }

This is my current code, and it works well on some runs but on other runs I get an ArrayIndexOutOfBounds on the first arraycopy method and I'm not sure why.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source