Junior — Middle
What are the differences between ArrayList and LinkedList implementations in Java?
sobes.tech AI
Answer from AI
ArrayList and LinkedList are two implementations of the List interface in Java, but they differ in internal structure and performance.
- ArrayList is based on a dynamic array. Fast access by index (O(1)), but insertions and deletions in the middle of the list require shifting elements (O(n)).
- LinkedList is implemented as a doubly linked list. Access by index is slower (O(n)), but inserting and deleting elements in the middle of the list is faster (O(1)), if there is a reference to the node.
Example:
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("A");
arrayList.add("B");
LinkedList<String> linkedList = new LinkedList<>();
linkedList.add("A");
linkedList.add("B");
The choice depends on the scenario: if you need quick random access — ArrayList, if you often insert/delete elements in the middle — LinkedList.