From this CodeReview answer,
You seem to use ArrayList for all purposes. There are other List-types in Java that suit certain situations better than an ArrayList. You should have a look at those and try to get a feeling when to use which list. In this particular case i.E. a LinkedList is better.
I also tend to use ArrayList
fairly heavily, and don't see the logic behind selecting another list type.
The List
docs show five main List
subclasses: ArrayList
, CopyOnWriteArrayList
, LinkedList
, Stack
, and Vector
.
From the ArrayList
docs,
The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.
This suggests that ArrayList
will often outperform LinkedList
(an assertion supported by this heavily upvoted question), although the LinkedList
docs don't give a good idea of performance:
All of the operations perform as could be expected for a doubly-linked list.
CopyOnWriteArrayList
only seems useful for unchanging lists, since the full snapshot on every modification seems ridiculously expensive for normal use.
Even the Stack
docs don't recommend using it:
A more complete and consistent set of LIFO stack operations is provided by the Deque interface and its implementations, which should be used in preference to this class.
Since Vector
is synchronized and the rest of the List
subclasses are not, it seems to me that Vector
would be the best choice in a threadsafe environment.
Even after reading through the docs, however, I still don't think I understand where TwoThe's answer came from. CopyOnWriteArrayList
and Vector
each seem to have one specialized use case, Stack
doesn't seem worth using, and ArrayList
seems superior to LinkedList
.
What am I missing here, and under what circumstances would another List
implementation be superior to ArrayList
?