Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

arraylist

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)?

like image 312
user2916610 Avatar asked Nov 17 '15 12:11

user2916610


People also ask

How do you remove an element from an ArrayList at a specific index?

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).

How do you remove all elements from an ArrayList in Java?

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);


1 Answers

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.

like image 98
Eran Avatar answered Nov 15 '22 04:11

Eran