LinkedList
A LinkedList is another important implementation of the
List interface in Java.
Unlike ArrayList, it does not store elements in a continuous memory block.
Instead, a LinkedList stores data as a chain of nodes, where each node contains the element and a reference to the next (and previous) node.
Why LinkedList Exists
ArrayList is very fast for reading data, but it becomes slower when frequent insertions or deletions happen in the middle of the list.
LinkedList solves this problem by allowing fast insertions and removals without shifting elements.
Key Characteristics of LinkedList
- Maintains insertion order
- Allows duplicate elements
- Efficient insertions and deletions
- Slower random access compared to ArrayList
Creating a LinkedList
A LinkedList is created using the LinkedList class
and usually referenced through the List interface.
import java.util.LinkedList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List cities = new LinkedList<>();
cities.add("New York");
cities.add("London");
cities.add("Tokyo");
System.out.println(cities);
}
}
Adding and Removing Elements
LinkedList provides efficient operations for adding and removing elements, especially at the beginning and middle of the list.
cities.add(1, "Paris");
cities.remove("London");
System.out.println(cities);
No shifting of elements is required internally.
Accessing Elements
LinkedList supports index-based access, but it is slower compared to ArrayList because traversal is required.
System.out.println(cities.get(0));
System.out.println(cities.get(2));
Real-World Example
Consider a music playlist where songs are frequently added or removed while playing.
List playlist = new LinkedList<>();
playlist.add("Song A");
playlist.add("Song B");
playlist.add("Song C");
playlist.remove("Song B");
playlist.add(1, "Song D");
System.out.println(playlist);
LinkedList works well in scenarios where list modification is frequent.
ArrayList vs LinkedList
- ArrayList – fast access, slower insert/delete
- LinkedList – slower access, faster insert/delete
Choosing between them depends on how the list is used.
When to Use LinkedList
- Frequent insertions or deletions
- Queue or deque operations
- Sequential access patterns
Key Takeaways
- LinkedList stores elements as nodes
- It is efficient for modifications
- It is less efficient for random access
- It complements ArrayList in real applications
In the next lesson, we will explore HashMap and understand key-value storage in Java.