Is this snippet unnecessary in the source code of Arraylist.remove (int index)?

Here is the source code:

Deletes an item at the specified position in this list. Shifts any subsequent elements to the left (subtracts one of their indices). Parameters: index the index of the item to be deleted. Returns: element that has been removed from the Throws list: 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:

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

+5
source share
2 answers

numMoved may be 0 (if you delete the last element by calling list.remove(list.size()-1) ), arraycopy is not required in this case. Therefore, if (numMoved > 0) needed.

+6
source

When you delete the last element of the list, index is size - 1 , in which case numMoved is 0, and numMoved is not required.

+5
source

Source: https://habr.com/ru/post/1236153/


All Articles