The cost of remove is O(n) , since you need to shuffle the elements above this point βleftβ by one. If your test code gives you O(1) , you will not measure it correctly :-)
An OpenJDK source, for example, has the following:
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; }
and System.arraycopy is the O(n) cost for this function.
Also, I'm not sure if you understood this well:
for (int i = 0; i < list.size() ; i++) list.remove(i);
This will remove the following items from the original list:
0, 2, 4, 8
etc., because the action of deleting element 0 shifts all other elements to the left - the element that was originally with offset 1 will be at offset 0 when you deleted the original offset 0, and then move to remove offset 1.
You would be better off:
list.remove(0);
inside the loop.
paxdiablo
source share