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)
?
The remove(int index) method present in java. util. ArrayList class removes the element at the specified position in this list and shifts any subsequent elements to the left (i.e. subtracts one from their indices).
The Java ArrayList removeAll() method removes all the elements from the arraylist that are also present in the specified collection. The syntax of the removeAll() method is: arraylist. removeAll(Collection c);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With