5

Here's the source code:

Removes the element at the specified position in this list. Shifts any subsequent elements to the left (subtracts one from their indices). Parameters: index the index of the element to be removed Returns: the element that was removed from the list Throws: java.lang.IndexOutOfBoundsException

public E remove(int index) {
    rangeCheck(index);
    modCount++;
    E oldValue = elementData(index);
    int numMoved = size - index - 1;
    if (numMoved > 0)
    System.arraycopy(elementData, index+1, elementData, index,
        numMoved);
    elementData[--size] = null; // Let gc do its work
    return oldValue;
}

My question is:

As the rangeCheck(index) has already guarantee that index < size, is it necessary to check that if (numMoved > 0)?

2 Answers 2

6

numMoved can be 0 (if you remove the last element by calling list.remove(list.size()-1)), in which case no arraycopy is required. Therefore the if (numMoved > 0) is necessary.

Sign up to request clarification or add additional context in comments.

Comments

5

When you remove the last element of the list, index is equal to size - 1, in which case numMoved is 0 and no System.arraycopy is required.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.