Java – queue implementation using circular arrays: which method can you adjust the size of circular arrays?
I'm using a circular array to implement a queue, and I'm a little stuck in the resize () method implementation (when the array is full)
In the enqueue () method, I check whether the size of the array is equal to its length, and if it is full, I check it Now, instead of throwing an exception, I try to resize the array
The problem is, I have two cases to consider
>What is the best way to copy the elements of the old array to the new larger array?
I think it uses a for loop, such as:
newArray = new Array[oldArray.length*2]; if (front <= rear) { for (int i = front; i < rear; i++) { newArray[i] = oldArray[i]; } } else { for (int i = front; i < newArray.length; i++) { newArray[i] = oldArray[i]; } for (int j = rear; j < front; j++) { // i'm using the variable i,the order is maintained newArray[i] = oldArray[j]; i++; } }
Then oldarray = newarray, return newarray and resize
I'm not sure how much to do it. I'm afraid I'll lose my values
Can someone tell me if there is a better way?
Solution
To copy an array with multiple elements, use system Arraycopy (), because it is usually implemented as native code, for example, sun's VM uses a manually encoded assembler
Front > rear
Because the data is continuous, it can remain in the same position in the new array
System.arraycopy(oldArray,front,newArray,front-rear);
The preceding < = the following data is discontinuous, so copy the two blocks to the beginning of the new array
// copy [rear to end] System.arraycopy(oldArray,rear,oldArray.length-rear); // copy [0 to front] System.arraycopy(oldArray,oldArray.length-rear,front); front = oldArray.length-(rear-front); rear = 0;