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)
Arrays will always be faster as compared to LinkedList.. Arrays store the data directly to a memory location.
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.
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.
So bottom line is ArrayList is better as it gives a similar or better performance depending on the version of Java.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With