1. Introduction
LinkedList is a part of the collection framework in Java and resides in the java.util package. Unlike ArrayList, the LinkedList class is a doubly-linked list that supports dynamic data storage. In this post, we’ll dive into the CRUD (Create, Read, Update, Delete) operations that can be executed on a LinkedList.
2. Program Steps
1. Initialize a LinkedList.
2. Insert elements into the LinkedList (Create).
3. Fetch elements from the LinkedList (Read).
4. Alter elements within the LinkedList (Update).
5. Extract elements from the LinkedList (Delete).
6. Display the resultant LinkedList.
3. Code Program
import java.util.LinkedList;
public class LinkedListCRUDExample {
public static void main(String[] args) {
// 1. Initialize a LinkedList
LinkedList<String> animals = new LinkedList<>();
// 2. Insert elements into the LinkedList (Create)
animals.add("Lion");
animals.add("Tiger");
animals.add("Bear");
System.out.println("After inserting elements: " + animals);
// 3. Fetch elements from the LinkedList (Read)
String firstAnimal = animals.get(0);
System.out.println("First animal: " + firstAnimal);
// 4. Alter elements within the LinkedList (Update)
animals.set(1, "Elephant");
System.out.println("After updating second element: " + animals);
// 5. Extract elements from the LinkedList (Delete)
animals.remove("Bear");
System.out.println("After removing Bear: " + animals);
// 6. Display the resultant LinkedList
System.out.println("Resultant LinkedList: " + animals);
}
}
Output:
After inserting elements: [Lion, Tiger, Bear] First animal: Lion After updating second element: [Lion, Elephant, Bear] After removing Bear: [Lion, Elephant]
4. Step By Step Explanation
1. We start by initializing an empty LinkedList named animals.
2. Three animals are then added to the list using the add method.
3. The get method, when supplied with the index of the desired element, is employed to retrieve an item from the list.
4. To update an element in the list, we employ the set method, providing both the index and the new value.
5. The remove method helps in deleting an element from the list. One can either provide the object directly or specify its index for removal.
6. At different intervals, we display the status of the LinkedList to visualize the modifications made.
The program offers a clear understanding of how CRUD operations are handled using a doubly-linked list in Java, with the LinkedList class serving as the cornerstone.