Looking at the source code of ArrayList
There appears to be quite different methods between remove object and remove index.
Would there be a way to perhaps grab the particular objects location and is the remove index number any faster than remove object function?
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;
}
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
private void fastRemove(int index) {
modCount++;
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index, numMoved);
elementData[--size] = null; // Let gc do its work
}
Initial tests of temporarily saving the index location during the iteration process appears to be about 5-10% faster.
myArrayList.remove(tempIndexInt) is 5-10% faster //remove int index
myArrayList.remove(this) //remove object
adding items to a removeme Arraylist to later remove that collection from the original list is slow.
adding items to a new list, to simply exclude “to be removed” items is even slower?
However, this isn’t a real world application, just a little test I setup. So I am not really sure how accurate setup is.