Java LinkedList
Learn Java through interactive, bite-sized lessons. Practice with real code challenges and build applications.
Start Java Journey →A LinkedList in Java is a doubly-linked list implementation of the List Interface. It provides efficient insertion and deletion operations, making it an excellent choice for certain types of data manipulation.
Key Features
- Implements List and Deque interfaces
- Allows duplicate elements
- Maintains insertion order
- Non-synchronized (not thread-safe)
- Can be used as a list, stack, or queue
Creating a LinkedList
To use a LinkedList, first import the java.util.LinkedList class. Then, you can create an instance:
import java.util.LinkedList;
LinkedList<String> list = new LinkedList<>();
Basic Operations
Adding Elements
LinkedList provides several methods to add elements:
list.add("Apple"); // Adds to the end
list.addFirst("Banana"); // Adds to the beginning
list.addLast("Cherry"); // Adds to the end
list.add(1, "Date"); // Adds at specific index
Removing Elements
Elements can be removed in various ways:
list.remove("Apple"); // Removes first occurrence
list.removeFirst(); // Removes first element
list.removeLast(); // Removes last element
list.remove(1); // Removes element at index 1
Advantages of LinkedList
- Efficient insertion and deletion at both ends (O(1) time complexity)
- Dynamic size, grows and shrinks as needed
- No need to specify initial capacity
- Implements both List and Deque interfaces, offering versatility
Considerations
- Slower random access compared to ArrayList (O(n) vs O(1))
- Uses more memory due to storage of additional pointers
- Not ideal for frequent random access or searching operations
Common Use Cases
LinkedList is particularly useful in scenarios where:
- Frequent insertions or deletions are required, especially at the beginning or end of the list
- You need to implement a queue or stack data structure
- The size of the collection changes frequently
- Random access is not a primary concern
Performance Comparison
| Operation | LinkedList | ArrayList |
|---|---|---|
| add(E) | O(1) | O(1) amortized |
| add(int, E) | O(n) | O(n) |
| get(int) | O(n) | O(1) |
| remove(int) | O(n) | O(n) |
Conclusion
Java LinkedList is a versatile data structure that excels in scenarios requiring frequent insertions and deletions. While it may not be the best choice for random access operations, its flexibility and efficiency in certain use cases make it an important tool in a Java developer's toolkit. Understanding its strengths and limitations allows you to make informed decisions when choosing the right data structure for your specific needs.