To answer the question, let's compare the remove methods of the ArrayList and ArrayDeque classes.
ArrayList remove method
public E remove(int index) {
this.rangeCheck(index);
++this.modCount;
E oldValue = this.elementData(index);
int numMoved = this.size - index - 1;
if (numMoved > 0) {
System.arraycopy(this.elementData, index + 1, this.elementData, index, numMoved);
}
this.elementData[--this.size] = null;
return oldValue;
}
ArrayDeque removeLast method
public E removeLast() {
E x = this.pollLast();
if (x == null) {
throw new NoSuchElementException();
} else {
return x;
}
}
ArrayDeque removeLast method calling pollLast method
public E pollLast() {
int t = this.tail - 1 & this.elements.length - 1;
E result = this.elements[t];
if (result == null) {
return null;
} else {
this.elements[t] = null;
this.tail = t;
return result;
}
}
Let's explain the ArrayList remove method step by step:
- Check if the entered index is within the limits of the array
- Increment the ModCount variable by one.
- Store the value to be deleted.
- Determine how many numbers to move (in our example, numMoved 0 is found because the last element will be deleted).
- Copy the array if the number to move is greater than 0 (the copy will not be performed because numMoved 0 is found).
- Assign null to the last element of the array.
- Return the deleted value.
Let's explain the ArrayDeque removeLast method step by step (it will suffice to explain the pollLast method):
- Find the last index of the array
- Return the value of the last element of the array.
- Return null if the value of the last element is equal to null.
- İf the value of the last element is not null (if it is not null, the following steps will occur).
- Assign null to last element
- Update the value of the tail variable
- Return result
When we compare the steps, there is no noticeable difference in terms of performance. In our example, ArrayList's System.copyarray
method will not work because we deleted the last element. If this method had worked, there would have been a performance difference. In conclusion there is no difference to be considered other than @Gerald Mücke's answer. If the element to be deleted was the first element of the list then there would be a performance difference. When we want to delete the first element, we can use the removeFirst
method of the ArrayDeque
class. (The removeFirst
method works similarly to the removeLast
method). When we want to delete the first element in ArrayList, we can use the remove(0)
method. When we delete the ArrayList with 0 index, this time the array copy(System.copyarray
) will be done. We used to say that ArrayList
is slower because of the array copying process.