I know that it's a never-ending question that comes back every now and then, but I'm really confused about these two. This is what I understand about them.
In theory:
- LinkedList is faster at adding elements at both ends (since there is no need for occasional resizing and copying of the list, which guarantees O(1) time without any special cases,
- Adding ONE ITEM to the middle of the list is O(n) in both cases, but still faster in ArrayList, since iterating over it is much faster
- Adding many items to the middle is O(1) in LinkedList if we already have a reference to the middle Node
In practice:
- LinkedList is slower at adding/removing from the end than ArrayList (I guess due to ArrayList using much less memory)
Which leaves me with one thought: LinkedList, in reality, is only better at adding/removing items from front and adding in the middle if we have a reference to the middle node. However, we can solve the problem of adding/removing in the beginning if we use ArrayDeque instead of it (as long as we don't care about random access). Then, LinkedList will be left with only one advantage - adding in the middle while having a reference there. If there is any other scenario, I should basically never use LinkedList. Is my thinking correct?
java.*are more or less nonexistent.ArrayList’saddAllmay still win…log₂ n, actually far less because we do not start with a capacity of one and only the few elements added at the beginning are copied each time while the majority of the elements are copied far less, the last added are usually written only once, half of them only experienced at most one copy operation. So, when adding to the end, the total number of writes is always smaller than forLinkedList.