Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a LinkedList or ArrayList for iteration

If I am be adding an unknown number of elements to a List, and that list is only going to be iterated through, would a LinkedList be better than an ArrayList in the particular instance (Using Java, if that has any relevance)

like image 671
Atrus Avatar asked Dec 08 '11 19:12

Atrus


People also ask

Which is faster to iterate LinkedList or array?

Arrays will always be faster as compared to LinkedList.. Arrays store the data directly to a memory location.

When would you use a LinkedList vs ArrayList?

LinkedList should be used where modifications to a collection are frequent like addition/deletion operations. LinkedList is much faster as compare to ArrayList in such cases. In case of read-only collections or collections which are rarely modified, ArrayList is suitable.

Can you iterate through a LinkedList?

An Iterator can be used to loop through an LinkedList. The method hasNext( ) returns true if there are more elements in LinkedList and false otherwise. The method next( ) returns the next element in the LinkedList and throws the exception NoSuchElementException if there is no next element.

Which is better for sorting ArrayList or LinkedList?

So bottom line is ArrayList is better as it gives a similar or better performance depending on the version of Java.


1 Answers

The performance trade-offs between ArrayList and LinkedList have been discussed before, but in short: ArrayList tends to be faster for most real-life usage scenarios. ArrayList will cause less memory fragmentation and will play nicer with the Garbage Collector, it will use up less memory and allow for faster iteration, and it will be faster for insertions that occur at the end of the list.

So, as long as the insertions in the list always occur at the last position, there's no reason to pick LinkedList - ArrayList is the clear winner.

like image 152
Óscar López Avatar answered Oct 09 '22 03:10

Óscar López