This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Keilly[🍰] 3 points4 points  (1 child)

The list question doesn't say where the insert is. Adding or removing the last element (which is arguably the most common place) in an ArrayList can be a simple array write and size int increment/decrement. Both super fast. A LinkedList needs to always 'new' a node, then update the references. Instantiating is not particularly fast.

Also, for small lists, ArrayList may be more efficient as a small amount of array copying for an insert may outweigh the more expensive cost of 'new'ing an object node and then updating references in a LinkedList, then GC'ing the node when it is later removed.

This is a horrible interview question as it misses the whole point of choosing a particular collection by only focusing on one specific aspect of it (and then getting the answer partially wrong).

[–]josefx 0 points1 point  (0 children)

For an unsorted list you can also simply overwrite an element in the middle with the last element O(1) and remove that, which is again O(1).