Java LinkedList
Introduction
Welcome to the Java Collections framework tutorial series. In this tutorial, we will learn everything about the LinkedList class in Java.
LinkedList
in Java is a part of the Java Collections Framework and implements the List
and Deque
interfaces. Unlike ArrayList
, which uses a dynamic array, LinkedList
uses a doubly linked list to store its elements. This structure allows for efficient insertions and deletions, but accessing elements by index is slower compared to ArrayList
.
Learn complete Java programming: https://www.rameshfadatare.com/learn-java-programming/
Table of Contents
- What is LinkedList?
- Key Points About LinkedList
- Creating a LinkedList and Adding Elements
- Accessing Elements in a LinkedList
- Modifying Elements in a LinkedList
- Removing Elements from a LinkedList
- Iterating Over a LinkedList
- Searching for Elements in a LinkedList
- LinkedList of User-Defined Objects
- All LinkedList Class Methods
- Difference Between ArrayList and LinkedList
- Conclusion
1. What is LinkedList?
A LinkedList
is a linear data structure that consists of a sequence of elements, where each element points to the next and the previous elements in the sequence. This makes it efficient for inserting and removing elements but less efficient for accessing elements by index.
2. Key Points About LinkedList
- Insertion Order: Java LinkedList maintains the insertion order of the elements
- Doubly Linked: Each element points to both its next and previous elements.
- Efficient Insertions/Deletions: Insertions and deletions are faster compared to
ArrayList
. - Slower Indexed Access: Accessing elements by index is slower compared to
ArrayList
. - Implements List and Deque: Supports methods from both
List
andDeque
interfaces. - Allows Duplicates and Nulls: Can contain duplicate elements and
null
values. - Not thread-safe: Java LinkedList is not thread-safe. You must explicitly synchronize concurrent modifications to the LinkedList in a multi-threaded environment.
3. Creating a LinkedList and Adding Elements
To create a LinkedList
, you can use the LinkedList
constructor. You can then use methods such as add
and addFirst
to add elements.
Example:
In this example, we create a LinkedList
of strings and add a few elements to it.
import java.util.LinkedList;
import java.util.List;
public class LinkedListExample {
public static void main(String[] args) {
// Creating a LinkedList
List<String> fruits = new LinkedList<>();
// Adding elements to the LinkedList
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
// Adding an element at the first position
((LinkedList<String>) fruits).addFirst("Mango");
// Displaying the LinkedList
System.out.println("LinkedList: " + fruits);
}
}
Output:
LinkedList: [Mango, Apple, Banana, Cherry]
4. Accessing Elements in a LinkedList
You can access elements in a LinkedList
using methods such as get
, getFirst
, and getLast
.
Example:
In this example, we demonstrate how to access elements in a LinkedList
.
import java.util.LinkedList;
import java.util.List;
public class AccessLinkedList {
public static void main(String[] args) {
// Creating a LinkedList
List<String> fruits = new LinkedList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
// Accessing elements
System.out.println("First element: " + ((LinkedList<String>) fruits).getFirst());
System.out.println("Last element: " + ((LinkedList<String>) fruits).getLast());
System.out.println("Element at index 1: " + fruits.get(1));
}
}
Output:
First element: Apple
Last element: Cherry
Element at index 1: Banana
5. Modifying Elements in a LinkedList
You can modify elements in a LinkedList
using methods such as set
.
Example:
In this example, we demonstrate how to modify elements in a LinkedList
.
import java.util.LinkedList;
import java.util.List;
public class ModifyLinkedList {
public static void main(String[] args) {
// Creating a LinkedList
List<String> fruits = new LinkedList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
// Modifying an element
fruits.set(1, "Blueberry");
// Displaying the updated LinkedList
System.out.println("Updated LinkedList: " + fruits);
}
}
Output:
Updated LinkedList: [Apple, Blueberry, Cherry]
6. Removing Elements from a LinkedList
You can remove elements from a LinkedList
using methods such as remove
, removeFirst
, and removeLast
.
Example:
In this example, we demonstrate how to remove elements from a LinkedList
.
import java.util.LinkedList;
import java.util.List;
public class RemoveLinkedList {
public static void main(String[] args) {
// Creating a LinkedList
List<String> fruits = new LinkedList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
// Removing elements
fruits.remove(1); // Remove element at index 1
((LinkedList<String>) fruits).removeFirst(); // Remove first element
((LinkedList<String>) fruits).removeLast(); // Remove last element
// Displaying the LinkedList
System.out.println("LinkedList after removals: " + fruits);
}
}
Output:
LinkedList after removals: []
7. Iterating Over a LinkedList
You can iterate over a LinkedList
using various methods such as Java 8 forEach
and lambda expressions, iterator
, listIterator
, simple for-each loop, and for loop with an index.
Example:
In this example, we demonstrate different ways to iterate over a LinkedList
.
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
public class IterateLinkedList {
public static void main(String[] args) {
// Creating a LinkedList
List<String> fruits = new LinkedList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
// Using Java 8 forEach and lambda expression
System.out.println("Using Java 8 forEach and lambda expression:");
fruits.forEach(fruit -> System.out.println(fruit));
// Using iterator
System.out.println("Using iterator:");
Iterator<String> iterator = fruits.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
// Using listIterator
System.out.println("Using listIterator:");
ListIterator<String> listIterator = fruits.listIterator();
while (listIterator.hasNext()) {
System.out.println(listIterator.next());
}
// Using simple for-each loop
System.out.println("Using simple for-each loop:");
for (String fruit : fruits) {
System.out.println(fruit);
}
// Using for loop with index
System.out.println("Using for loop with index:");
for (int i = 0; i < fruits.size(); i++) {
System.out.println(fruits.get(i));
}
}
}
Output:
Using Java 8 forEach and lambda expression:
Apple
Banana
Cherry
Using iterator:
Apple
Banana
Cherry
Using listIterator:
Apple
Banana
Cherry
Using simple for-each loop:
Apple
Banana
Cherry
Using for loop with index:
Apple
Banana
Cherry
8. Searching for Elements in a LinkedList
You can search for elements in a LinkedList
using methods such as contains
, indexOf
, and lastIndexOf
.
Example:
In this example, we demonstrate how to check if a LinkedList
contains a given element, find the index of the first occurrence of an element, and find the index of the last occurrence of an element.
import java.util.LinkedList;
import java.util.List;
public class SearchLinkedList {
public static void main(String[] args) {
// Creating a LinkedList
List<String> fruits = new LinkedList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
fruits.add("Banana");
// Check if the LinkedList contains a given element
System.out.println("Does the LinkedList contain 'Banana'? " + fruits.contains("Banana"));
// Find the index of the first occurrence of an element
System.out.println("Index of the first occurrence of 'Banana': " + fruits.indexOf("Banana"));
// Find the index of the last occurrence of an element
System.out.println("Index of the last occurrence of 'Banana': " + fruits.lastIndexOf("Banana"));
}
}
Output:
Does the LinkedList contain 'Banana'? true
Index of the first occurrence of 'Banana': 1
Index of the last occurrence of 'Banana': 3
9. LinkedList of User-Defined Objects
You can use LinkedList
to store user-defined objects. This involves creating a class for the objects you want to store and then creating a LinkedList
to manage these objects.
Example:
In this example, we create a Person
class and then create a LinkedList
to store Person
objects.
import java.util.LinkedList;
import java.util.List;
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
}
}
public class UserDefinedObjectLinkedList {
public static void main(String[] args) {
// Creating a LinkedList of Person objects
List<Person> people = new LinkedList<>();
people.add(new Person("Alice", 30));
people.add(new Person("Bob", 25));
people.add(new Person("Charlie", 35));
// Displaying the LinkedList
System.out.println("LinkedList of Person objects: " + people);
}
}
Output:
LinkedList of Person objects: [Person{name='Alice', age=30}, Person{name='Bob', age=25}, Person{name='Charlie', age=35}]
10. All LinkedList Class Methods
- Java LinkedList add() Method
- Java LinkedList addAll() Method
- Java LinkedList addFirst() Method
- Java LinkedList addLast() Method
- Java LinkedList clone() Method
- Java LinkedList clear() Method
- Java LinkedList contains() Method
- Java LinkedList element() Method
- Java LinkedList descendingIterator() Method
- Java LinkedList get() Method
- Java LinkedList getFirst() Method
- Java LinkedList getLast() Method
- Java LinkedList indexOf() Method
- Java LinkedList lastIndexOf() Method
- Java LinkedList listIterator() Method
- Java LinkedList offer() Method
- Java LinkedList offerFirst() Method
- Java LinkedList offerLast() Method
- Java LinkedList peek() Method
- Java LinkedList peekFirst() Method
- Java LinkedList peekLast() Method
- Java LinkedList poll() Method
- Java LinkedList pollFirst() Method
- Java LinkedList pollLast() Method
- Java LinkedList pop() Method
- Java LinkedList push() Method
- Java LinkedList remove() Method
- Java LinkedList removeFirst() Method
- Java LinkedList removeFirstOccurrence() Method
- Java LinkedList removeLast() Method
- Java LinkedList removeLastOccurrence() Method
- Java LinkedList set() Method
- Java LinkedList size() Method
- Java LinkedList toArray() Method
11. Difference Between ArrayList and LinkedList
12. Conclusion
LinkedList
in Java is a versatile data structure that provides efficient insertions and deletions, making it suitable for applications where frequent modifications are required. However, it is less efficient for accessing elements by index compared to ArrayList
.
Understanding the use cases, benefits, and limitations of LinkedList
can help you choose the right data structure for your application. With methods from both the List
and Deque
interfaces, LinkedList
offers a wide range of functionalities to manage collections effectively.
Original Post:
https://www.rameshfadatare.com/java-programming/java-linkedlist/