Introduction
A LinkedList
in Java is a part of the Java Collections Framework and implements the List
and Deque
interfaces. Unlike an ArrayList
, which uses a dynamic array to store elements, a LinkedList
uses a doubly linked list to store elements. This structure allows for efficient insertion and removal of elements from any position in the list.
Key Concepts
- Doubly Linked List: Each element (node) contains a reference to the previous and next node.
- Dynamic Size: The size of a
LinkedList
can grow and shrink dynamically. - Performance: Insertion and deletion operations are generally faster than in an
ArrayList
, especially for large lists.
LinkedList vs ArrayList
Feature | LinkedList | ArrayList |
---|---|---|
Data Structure | Doubly Linked List | Dynamic Array |
Access Time | O(n) (linear time) | O(1) (constant time) |
Insertion/Deletion | O(1) (constant time) for adding/removing at the beginning or end | O(n) (linear time) |
Memory Overhead | More (due to storing two references per node) | Less |
Creating a LinkedList
To create a LinkedList
, you need to import java.util.LinkedList
and instantiate it:
import java.util.LinkedList; public class LinkedListExample { public static void main(String[] args) { LinkedList<String> list = new LinkedList<>(); // Adding elements list.add("Apple"); list.add("Banana"); list.add("Cherry"); // Displaying the LinkedList System.out.println("LinkedList: " + list); } }
Explanation
- Import Statement:
import java.util.LinkedList;
imports theLinkedList
class. - Instantiation:
LinkedList<String> list = new LinkedList<>();
creates a newLinkedList
of typeString
. - Adding Elements:
list.add("Apple");
adds elements to the list. - Displaying Elements:
System.out.println("LinkedList: " + list);
prints the list.
Common Operations
Adding Elements
You can add elements at the beginning, end, or at a specific position:
list.addFirst("Mango"); // Adds at the beginning list.addLast("Orange"); // Adds at the end list.add(2, "Grapes"); // Adds at index 2
Removing Elements
You can remove elements by value, index, or from the beginning/end:
list.remove("Banana"); // Removes the first occurrence of "Banana" list.remove(1); // Removes the element at index 1 list.removeFirst(); // Removes the first element list.removeLast(); // Removes the last element
Accessing Elements
You can access elements using get
and peek
methods:
String firstElement = list.getFirst(); // Retrieves the first element String lastElement = list.getLast(); // Retrieves the last element String elementAtIndex = list.get(2); // Retrieves the element at index 2
Iterating Over Elements
You can iterate over the elements using a for-each
loop or an iterator:
// Using for-each loop for (String fruit : list) { System.out.println(fruit); } // Using iterator Iterator<String> iterator = list.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); }
Practical Exercise
Task
Create a LinkedList
of integers, add elements to it, remove some elements, and iterate over the list to print the remaining elements.
Solution
import java.util.LinkedList; import java.util.Iterator; public class LinkedListExercise { public static void main(String[] args) { LinkedList<Integer> numbers = new LinkedList<>(); // Adding elements numbers.add(10); numbers.add(20); numbers.add(30); numbers.add(40); numbers.add(50); // Removing elements numbers.remove(2); // Removes the element at index 2 (30) numbers.removeFirst(); // Removes the first element (10) numbers.removeLast(); // Removes the last element (50) // Iterating over the list Iterator<Integer> iterator = numbers.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } } }
Explanation
- Adding Elements: Adds integers to the
LinkedList
. - Removing Elements: Removes elements at specific positions.
- Iterating: Uses an iterator to print the remaining elements.
Common Mistakes
- IndexOutOfBoundsException: Ensure the index is within the valid range when accessing or removing elements.
- ConcurrentModificationException: Avoid modifying the list while iterating over it using an iterator.
Conclusion
In this section, you learned about the LinkedList
class in Java, its key features, and how it compares to ArrayList
. You also practiced common operations such as adding, removing, and accessing elements, and iterating over the list. Understanding LinkedList
is crucial for efficient data manipulation in Java, especially when frequent insertions and deletions are required.
Java Programming Course
Module 1: Introduction to Java
- Introduction to Java
- Setting Up the Development Environment
- Basic Syntax and Structure
- Variables and Data Types
- Operators
Module 2: Control Flow
Module 3: Object-Oriented Programming
- Introduction to OOP
- Classes and Objects
- Methods
- Constructors
- Inheritance
- Polymorphism
- Encapsulation
- Abstraction
Module 4: Advanced Object-Oriented Programming
Module 5: Data Structures and Collections
Module 6: Exception Handling
Module 7: File I/O
Module 8: Multithreading and Concurrency
- Introduction to Multithreading
- Creating Threads
- Thread Lifecycle
- Synchronization
- Concurrency Utilities
Module 9: Networking
- Introduction to Networking
- Sockets
- ServerSocket
- DatagramSocket and DatagramPacket
- URL and HttpURLConnection