I was reading The Art of Computer Programming Vol 1, the chapter about arrays and list. Knuth describes the differences and mentions how it’s very easy to add a new element to a list in a constant time if we have the node where the insertion needs to happen. Same for deletion. That is when I realized I did not know how the ArrayList implementation handles it. I did a code walk through of that class – something Prasun had advised me long ago but I always ignored.
I always knew that ArrayList used array for implementation, which is how it can guarantee the O(1) element access time. But I did not know how the other methods worked. For instance, one need not provide any initial size of the ArrayList. How does Java handle it? I remember Prasun telling me that the initial size in such cases is 10. But then what happens in the case of an overflow? What is the new space that gets assigned to the list?
But I was more interested in the add(index, element) and the remove(index) methods. And they are not constant time! They are O(n) operations. Say we want to remove(6). Java actually copies over all the elements from 7..n to indexes 6..n-1 and then sets the nth element as null. This is so not what we learn as deletion in list where it was just a matter of changing a couple of pointers (the next and prev ones).
Popularity: 2% [?]
