r/learnjava • • 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

15 comments sorted by

View all comments

61

u/feral_claire Dec 21 '20

In practice, pretty much always chose ArrayList over LinkedList. It's usually the better choice.

ArrayList is better at appending to and removing at the end, iteration, and random access. It also uses way less memory (LinkedList uses about 5 times as much).

The only think LinkedList is better is, is adding and removing from the front of the list. It's only better at adding or removing in the middle of the list if you do it while already iterating the list, since you need to loop through the list to get to a specific index, it's still faster with ArrayList if you want to insert a random index even though it means copying the list to make room.

The reason adding and removing at the end is so much faster is because you are just setting a value in the array versus needing to create a whole node object and set a pointer to it. Yes you need to resize the array sometimes but since the array in ArrayList is oversized you rarely need to do it doesn't make a big impact. Copying arrays is also very fast.

6

u/maybe_tom__ Dec 21 '20 edited Dec 21 '20

Thank you! This is very usefull and instructive ❤️✌🏻

EDIT: (I've wait for a free award to give it to you, ty again ✌🏻😁)

2

u/TheMaveric_2187 Dec 21 '20

I gave him mine.