I'm trying to find a way to implement an efficient clear
to clear a circular array queue in constant time.
I've tried Array.fill()
and filled the array with null
values but it still has to go through the array which means O(n).
I'm trying to find a way to implement an efficient clear
to clear a circular array queue in constant time.
I've tried Array.fill()
and filled the array with null
values but it still has to go through the array which means O(n).
I would say the answer to this question depends a bit on your requirements and what counts as a constant operation.
head
and tail
pointers around. However, be aware that this doesn't clean out the references to the (perhaps heavyweight) objects in the array, which might result in a memory leak in your application, because the objects still stored in there can't be garbage collected.Looking at the implementation of the clear
operation of ArrayDeque
(which basically is just a circular array queue), you can see that it uses an O(n) approach through the following two operations: (1) nulling the elements, (2) resetting the pointers.
/**
* Removes all of the elements from this deque.
* The deque will be empty after this call returns.
*/
public void clear() {
circularClear(elements, head, tail);
head = tail = 0;
}
/**
* Nulls out slots starting at array index i, upto index end.
* Condition i == end means "empty" - nothing to do.
*/
private static void circularClear(Object[] es, int i, int end) {
// assert 0 <= i && i < es.length;
// assert 0 <= end && end < es.length;
for (int to = (i <= end) ? end : es.length;
; i = 0, to = end) {
for (; i < to; i++) es[i] = null;
if (to == end) break;
}
}