LinkedList is part of the Java Collections Framework and implements both the List and Deque interfaces. Unlike an ArrayList, which uses a dynamic array, LinkedList is a doubly linked list structure where each element (node) stores a reference to both the next and previous elements.
This makes it efficient for insertion and deletion operations at both ends.
In this tutorial, we'll explore how to use LinkedList in Java, including common operations with various code examples.
1. Creating a LinkedList
To create a LinkedList, you can declare it with any data type. You can create a list to store String, Integer, or any other object type.
Example:
import java.util.LinkedList; public class LinkedListExample { public static void main(String[] args) { // Creating a LinkedList of String type LinkedList fruits = new LinkedList<>(); // Adding elements to the LinkedList fruits.add("Apple"); fruits.add("Banana"); fruits.add("Cherry"); // Displaying the LinkedList System.out.println("LinkedList: " + fruits); } }
Explanation:
A LinkedList of type String is created.
The add() method adds elements to the list.
Output:
LinkedList: [Apple, Banana, Cherry].
2. Adding Elements to a LinkedList
Elements can be added at the beginning, end, or at a specific position in the LinkedList.
Example:
import java.util.LinkedList; public class AddElements { public static void main(String[] args) { LinkedList numbers = new LinkedList<>(); // Adding elements to the LinkedList numbers.add(10); // Add to the end numbers.add(20); // Add to the end // Adding element at the first position numbers.addFirst(5); // Adding element at the last position numbers.addLast(30); // Adding element at a specific index numbers.add(2, 15); // Adds 15 at index 2 // Displaying the LinkedList System.out.println("LinkedList: " + numbers); } }
Explanation:
addFirst() inserts an element at the beginning.
addLast() inserts an element at the end.
add(index, element) inserts an element at a specific index.
Output:
LinkedList: [5, 10, 15, 20, 30].
3. Accessing Elements in a LinkedList
Elements can be accessed using methods like get(), getFirst(), and getLast().
Example:
import java.util.LinkedList; public class AccessElements { public static void main(String[] args) { LinkedList fruits = new LinkedList<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Cherry"); // Accessing elements String firstFruit = fruits.getFirst(); String lastFruit = fruits.getLast(); String secondFruit = fruits.get(1); // Accessing the element at index 1 System.out.println("First Fruit: " + firstFruit); System.out.println("Second Fruit: " + secondFruit); System.out.println("Last Fruit: " + lastFruit); } }
Explanation:
getFirst() retrieves the first element.
getLast() retrieves the last element.
get(index) retrieves the element at the specified index.
Output:
First Fruit: Apple Second Fruit: Banana Last Fruit: Cherry
4. Removing Elements from a LinkedList
You can remove elements from the beginning, end, or any specific index using removeFirst(), removeLast(), or remove(index).
Example:
import java.util.LinkedList; public class RemoveElements { public static void main(String[] args) { LinkedList fruits = new LinkedList<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Cherry"); // Removing the first and last elements String removedFirst = fruits.removeFirst(); String removedLast = fruits.removeLast(); // Removing an element at a specific index String removedAtIndex = fruits.remove(0); // Removes the element at index 0 System.out.println("Removed First: " + removedFirst); System.out.println("Removed Last: " + removedLast); System.out.println("Removed at Index 0: " + removedAtIndex); System.out.println("LinkedList after removals: " + fruits); } }
Explanation:
removeFirst() removes and returns the first element.
removeLast() removes and returns the last element.
remove(index) removes the element at the specified index.
Output:
Removed First: Apple Removed Last: Cherry Removed at Index 0: Banana LinkedList after removals: []
5. Iterating Over a LinkedList
You can iterate over a LinkedList using a for-each loop, iterator, or the forEach() method with lambda expressions.
Example Using For-Each Loop:
import java.util.LinkedList; public class IterateLinkedList { public static void main(String[] args) { LinkedList fruits = new LinkedList<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Cherry"); // Iterating using for-each loop for (String fruit : fruits) { System.out.println(fruit); } } }
Example Using Lambda Expression:
import java.util.LinkedList; public class IterateWithLambda { public static void main(String[] args) { LinkedList fruits = new LinkedList<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Cherry"); // Iterating using forEach and lambda expression fruits.forEach(fruit -> System.out.println(fruit)); } }
Explanation:
Both examples iterate over the elements of the LinkedList and print them. The output will be:
Apple Banana Cherry
6. Checking if LinkedList is Empty
You can check whether the LinkedList is empty or not using the isEmpty() method.
Example:
import java.util.LinkedList; public class CheckEmpty { public static void main(String[] args) { LinkedList fruits = new LinkedList<>(); // Checking if the LinkedList is empty boolean isEmpty = fruits.isEmpty(); System.out.println("Is LinkedList empty? " + isEmpty); // Adding an element fruits.add("Apple"); // Checking again after adding an element isEmpty = fruits.isEmpty(); System.out.println("Is LinkedList empty? " + isEmpty); } }
Explanation:
isEmpty() returns true if the LinkedList contains no elements, false otherwise.
Output:
Is LinkedList empty? true Is LinkedList empty? false
7. LinkedList Size
To get the number of elements in a LinkedList, you can use the size() method.
Example:
import java.util.LinkedList; public class LinkedListSize { public static void main(String[] args) { LinkedList fruits = new LinkedList<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Cherry"); // Getting the size of the LinkedList int size = fruits.size(); System.out.println("Size of LinkedList: " + size); } }
Explanation:
size() returns the number of elements in the LinkedList.
Output:
Size of LinkedList: 3.
8. Using LinkedList as a Queue
Since LinkedList implements the Deque interface, it can be used as both a queue (FIFO) and a stack (LIFO). Below is an example of using it as a queue.
Example:
import java.util.LinkedList; public class LinkedListAsQueue { public static void main(String[] args) { LinkedList queue = new LinkedList<>(); // Enqueue elements queue.addLast("John"); queue.addLast("Alice"); queue.addLast("Bob"); // Dequeue elements System.out.println("Dequeued: " + queue.removeFirst()); // Dequeue first element (John) System.out.println("Dequeued: " + queue.removeFirst()); // Dequeue second element (Alice) // Display the remaining elements System.out.println("Remaining in queue: " + queue); } }
Explanation:
addLast() enqueues elements at the end of the list.
removeFirst() dequeues elements from the front.
Output:
Dequeued: John Dequeued: Alice Remaining in queue: [Bob]
9. Using LinkedList as a Stack
You can also use a LinkedList as a stack (LIFO).
Example:
import java.util.LinkedList; public class LinkedListAsStack { public static void main(String[] args) { LinkedList stack = new LinkedList<>(); // Push elements onto the stack stack.addFirst("John"); stack.addFirst("Alice"); stack.addFirst("Bob"); // Pop elements from the stack System.out.println("Popped: " + stack.removeFirst()); // Pop top element (Bob) System.out.println("Popped: " + stack.removeFirst()); // Pop second element (Alice) // Display the remaining elements System.out.println("Remaining in stack: " + stack); } }
Explanation:
addFirst() pushes elements onto the stack.
removeFirst() pops elements from the stack (LIFO behavior).
Output:
Popped: Bob Popped: Alice Remaining in stack: [John]
10. Clearing All Elements in a LinkedList
To remove all elements from a LinkedList, you can use the clear() method.
Example:
import java.util.LinkedList; public class ClearLinkedList { public static void main(String[] args) { LinkedList fruits = new LinkedList<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Cherry"); // Clearing the LinkedList fruits.clear(); // Checking if the LinkedList is empty System.out.println("Is LinkedList empty? " + fruits.isEmpty()); } }
Explanation:
The clear() method removes all elements from the LinkedList.
Output:
Is LinkedList empty? true.
Conclusion
LinkedList is an essential part of the Java Collections Framework that allows for efficient insertion and deletion at both ends of the list.
It can be used as a list, queue, or stack, and is particularly useful when you need fast insertions and deletions from the middle or ends of the list.
This tutorial has covered the most common operations you'll need to perform with a LinkedList, including adding, removing, accessing, and iterating over elements. Each example is designed to showcase a different feature of the LinkedList in Java.