r/learnjava • u/maybe_tom__ • Dec 21 '20
ArrayList vs LinkedList
Hi everyone, i want to solve a thought about ArrayList vs LinkedList. I know that ArrayList are basically an resizable array that start from a initial size of 10 (if not otherwise specified in constructor) that is resized everytime you try to put something over its actual length, and LinkedList have items that have pointers to next and previous Object. So linked list are more efficient with removing, adding and set items in the list, cause you don't have to resize all the array or reorder elements but you only change pointers... so the point is -> Why i would choose to use an ArrayList instead LinkedList?
46
Upvotes
9
u/JasburyCS Dec 21 '20
The general rule of thumb: ArrayLists will be better any time you won’t be doing a lot of elements shifting and any time you need to randomly access any specific index efficiently (using .get() in Java if I remember correctly). This snowballs fast because many sorting algorithms, for example, rely on indexing. Most problems fall under this category.
Conversely, Linked lists are good at being dynamic if you plan on doing many operations that would cause an entire array to be shifted. This could include adding to the middle, removing from the middle, or adding/removing from the front of the list.
In general, yes an array list will solve most problems. Linked lists have more niche use cases. And in practice a lot of it will come to what your data looks like. Sure, copying array elements is fast in Java. But what what happens if the amount of data you have to copy to shift elements over becomes huge? And these shifts happen over and over again in your code? That’s when linked lists start to look more appealing