I'm trying to learn about the implementation of a circular queue using arrays, and currently, my main source of learning how it works is through this page.
https://www.happycoders.eu/algorithms/implement-deque-using-array/
However, I'm struggling to understand how one method in the code works, and that is the growToNewCapacity()
method. I've provided the code down below.
public class ArrayDeque<E> {
private static final int DEFAULT_INITIAL_CAPACITY = 10;
private Object[] elements;
private int headIndex;
private int tailIndex;
private int numberOfElements;
public ArrayDeque() {
this(DEFAULT_INITIAL_CAPACITY);
}
public ArrayDeque(int capacity) {
if (capacity < 1) {
throw new IllegalArgumentException("Capacity must be 1 or higher");
}
elements = new Object[capacity];
}
private void growToNewCapacity(int newCapacity) {
Object[] newArray = new Object[newCapacity];
int oldArrayLength = elements.length;
int numberOfElementsAfterTail = oldArrayLength - tailIndex;
System.arraycopy(elements, tailIndex, newArray, 0, numberOfElementsAfterTail);
if (tailIndex > 0) {
System.arraycopy(elements, 0, newArray, numberOfElementsAfterTail, tailIndex);
}
headIndex = 0;
tailIndex = oldArrayLength;
elements = newArray;
}
I'm just completely lost after the second line of the method which states
Object[] newArray = new Object[newCapacity];
int oldArrayLength = elements.length;
Anything beyond that is completely dumbfounded for me, so can anyone please take some time off to explain what exactly is going on with the code, so that I could implement it based on my understanding later on.