Junior
What are the main differences between List and LinkedList in Java?
sobes.tech AI
Answer from AI
List - an interface representing an ordered collection of elements. LinkedList is one of the implementations of the List interface.
Main differences:
-
Internal structure:
ArrayListuses a dynamic array.LinkedListuses a doubly linked list.
-
Performance of operations:
- Adding/removing in the middle:
LinkedListis faster as it only requires changing links (O(1) after locating the position).ArrayListrequires shifting elements (O(n)). - Adding/removing at the end:
ArrayListis faster (O(1) on average).LinkedListalso O(1). - Adding/removing at the beginning:
LinkedListis faster (O(1)).ArrayListrequires shifting elements (O(n)). - Access by index (get):
ArrayListis faster as it is based on an array (O(1)).LinkedListrequires traversal (O(n)). - Iteration: Both collections have similar performance when traversing elements with an iterator.
- Adding/removing in the middle:
-
Memory usage:
LinkedListrequires more memory per element as it needs to store references to the previous and next elements, in addition to the value itself.ArrayListstores only values.
-
Implemented interfaces:
- Both implement
List.LinkedListadditionally implementsDequeandQueue.
- Both implement
Summary table:
| Operation | ArrayList | LinkedList |
|---|---|---|
| Access by index | O(1) | O(n) |
| Add at the end | O(1) | O(1) |
| Add at the beginning | O(n) | O(1) |
| Add in the middle | O(n) | O(1) |
| Remove from end | O(1) | O(1) |
| Remove from beginning | O(n) | O(1) |
| Remove from middle | O(n) | O(1) |
| Iteration | O(n) | O(n) |
Choosing between ArrayList and LinkedList depends on the predominant operations to be performed on the collection. If frequent index access or frequent add/remove operations at the end are required, ArrayList is preferable. If frequent add/remove operations at the beginning or middle are needed, LinkedList will be more efficient.