Senior
What are the advantages of ArrayList vs LinkedList in terms of memory and performance?
sobes.tech AI
Answer from AI
ArrayList and LinkedList have different characteristics in memory and performance:
-
Memory:
- ArrayList stores elements in a contiguous array, which saves memory as there are no additional references.
- LinkedList stores each element in a separate node, which contains references to the previous and next elements, increasing memory consumption.
-
Performance:
- ArrayList provides quick access by index (O(1)), but inserting or deleting in the middle of the list requires shifting elements (O(n)).
- LinkedList is slower for index access (O(n)), but inserting and deleting in the middle of the list is faster (O(1)) if there is a reference to the node.
Example:
ArrayList<Integer> arrayList = new ArrayList<>();
LinkedList<Integer> linkedList = new LinkedList<>();
// Fast access by index
int val = arrayList.get(10); // fast
val = linkedList.get(10); // slow
// Inserting in the middle
arrayList.add(5, 100); // requires shifting elements
linkedList.add(5, 100); // just changes references
The choice depends on the use case: if fast index access is needed — ArrayList, if frequent insertions/deletions in the middle — LinkedList.