Learn the differences between ArrayList and LinkedList in Java and understand when to use each data structure effectively.
ArrayList is a resizable array implementation in Java’s Collection Framework. It allows dynamic storage of elements and provides fast access using indexes.
Example:
import java.util.ArrayList;
class ArrayListExample {
public static void main(String[] args) {
ArrayList list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Orange");
System.out.println(list);
}
}
LinkedList is a doubly-linked list implementation of the List and Deque interfaces. Each element points to the previous and next node, allowing efficient insertions and deletions.
Example:
import java.util.LinkedList;
class LinkedListExample {
public static void main(String[] args) {
LinkedList list = new LinkedList<>();
list.add("Apple");
list.add("Banana");
list.add("Orange");
System.out.println(list);
}
}
| Aspect | ArrayList | LinkedList |
|---|---|---|
| Data Structure | Resizable array | Doubly linked list |
| Access Time | Fast random access (O(1)) | Slow random access (O(n)) |
| Insertion / Deletion | Costly in middle (O(n)) | Fast in middle (O(1)) |
| Memory Usage | Less memory overhead | Higher memory (pointers for prev/next) |
| Use Case | Frequent access, less modification | Frequent insertion/deletion |
ArrayList: Fast access, simple implementation
LinkedList: Efficient insertion/deletion, can act as Queue/Deque
ArrayList: Slow insertion/deletion in middle, resizing overhead
LinkedList: Slower access, more memory usage
Use ArrayList when frequent access and fewer modifications are required.
Use LinkedList when frequent insertions/deletions in middle are expected.
Understand memory trade-offs between the two implementations.