Search code examples
javacollectionsarraydeque

method clear() in ArrayDeque


Why in ArrayDeque for clear this one, using (1)do-while for removing every element instead create new array with start size and (2)overwrite array where contains elements?

(1)

public void clear() {
    int h = head;
    int t = tail;
    if (h != t) { // clear all cells
        head = tail = 0;
        int i = h;
        int mask = elements.length - 1;
        do {
            elements[i] = null;
            i = (i + 1) & mask;
        } while (i != t);
    }
}

(2)

public void clear() {
     head = tail = 0;
     elements = null;
     elements = (T[]) Object[START_SIZE]; 
}

Solution

  • The reason you would want to explicitly set each element to null in clear() is that otherwise you could introduce a form of memory leak. That is, the elements[] array could hold onto references to objects and prevent them from being garbage collected.

    Your alternative of recreating the array from scratch would work (I think you're missing a new though), but allocating a new chunk of memory is generally slower than clearing one you've already been allocated.