LinkedList vs ArrayList on a specific android example
This question already has an answer here:
Short answer you should go for LinkedList
if you are adding/removing/updating element frequently, especially for the case of first/last elements, as it contains a pointer to the first and last node
Long answer LinkedList
add method gives O(1)
performance while ArrayList gives O(n)
in the worst case. LinkedList
is faster. It will just reference the nodes so the first one disappears:
In addition, ArrayList
is good for write-once-read-many or appenders, but bad at add/remove from the front or middle.
For instance, removing an element from a linked list costs O(1)
, while doing so for an array (array list) costs O(n)
.
But , this is not always a rule, as bigoh post states:
Big-oh notation can give very good ideas about performance for large amounts of data, but the only real way to know for sure is to actually try it with large data sets. There may be performance issues that are not taken into account by big-oh notation, eg, the effect on paging as virtual memory usage grows. Although benchmarks are better, they aren't feasible during the design process, so Big-Oh complexity analysis is the choice.
The above is validated with this post, where LinkedList
also proved slow.
Finally, for further/future reference, please take a look at the use case comparison of them, according to javaconceptoftheday.com:
References
http://docs.oracle.com/javase/8/docs/api/java/util/LinkedList.html http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html