Vlad Pavliuk
Vlad Pavliuk

Reputation: 65

Method remove() of Iterator in LinkedList

Could someone explain me how this method works, via. this place if (next == lastReturned). I do not understand in which case next can be equal lastReturned.

public void remove() {
        checkForComodification();
        if (lastReturned == null)
            throw new IllegalStateException();

        Node<E> lastNext = lastReturned.next;
        unlink(lastReturned);
        if (next == lastReturned)
            next = lastNext;
        else
            nextIndex--;
        lastReturned = null;
        expectedModCount++;
    }

Thank for answer!

Upvotes: 1

Views: 165

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1073968

lastReturned can also be next if the iterator's previous method has just been used:

public E previous() {
    checkForComodification();
    if (!hasPrevious())
        throw new NoSuchElementException();

    lastReturned = next = (next == null) ? last : next.prev; // <=====
    nextIndex--;
    return lastReturned.item;
}

So in that case (previous() then remove()), it's important that remove set next to the next item after the one that was just removed, which is what that if (next == lastRemoved) is doing.

Upvotes: 2

Related Questions