1. Introduction
In Java, the LinkedList class, part of the Collections Framework, provides the size() method to determine the number of elements in the linked list. This method is essential when we perform operations like iteration or indexing, where knowing the size of the list is crucial.
2. Program Steps
1. Create and initialize a LinkedList.
2. Print the size of the LinkedList using the size() method.
3. Add more elements to the LinkedList.
4. Again, print the updated size of the LinkedList.
3. Code Program
import java.util.LinkedList;
public class LinkedListSizeExample {
public static void main(String[] args) {
// Step 1: Create and initialize a LinkedList
LinkedList<String> fruits = new LinkedList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
// Step 2: Print the size of the LinkedList
System.out.println("Size of LinkedList: " + fruits.size());
// Step 3: Add more elements to the LinkedList
fruits.add("Mango");
fruits.add("Orange");
// Step 4: Again, print the updated size of the LinkedList
System.out.println("Updated Size of LinkedList: " + fruits.size());
}
}
Output:
Size of LinkedList: 3 Updated Size of LinkedList: 5
4. Step By Step Explanation
Step 1: A LinkedList named fruits is created and initialized with three elements: "Apple", "Banana", and "Cherry".
Step 2: The size() method is called on the fruits LinkedList to obtain and print its size, which is 3 at this point.
Step 3: Two more elements, "Mango" and "Orange", are added to the LinkedList.
Step 4: The size() method is again called on the updated fruits LinkedList, and the new size, which is now 5, is printed to the console.