Write a Java program to Get the number of elements in a LinkedList


The code demonstrates how to get the number of elements in a LinkedList in Java. The Number_Elements class contains a main method where a LinkedList object named list is created and populated with string elements using the add method.

The System.out.println statements are used to print the initial state of the list linked list and the number of elements in it using the size() method. The size() method is called on the list linked list to retrieve the number of elements in it. It returns an integer value representing the size or number of elements in the linked list.

As a result, the initial state of the list linked list will be printed using the System.out.println("LinkedList : "+list) statement, and the number of elements in it will be printed using the System.out.println("Number of Elements : "+list.size()) statement.

Source Code

import java.util.*;
public class Number_Elements
{
	public static void main(String[] args)
	{
		LinkedList<String> list = new LinkedList<String>();
		list.add("Apple"); 
		list.add("Mango");     
		list.add("Pineapple");  
		list.add("Cherry");    
		list.add("Guava");
		list.add("Banana");
		list.add("Watermelon");
		System.out.println("LinkedList : "+list); 
		System.out.println("Number of Elements : "+list.size());
	}
}

Output

LinkedList : [Apple, Mango, Pineapple, Cherry, Guava, Banana, Watermelon]
Number of Elements : 7

Example Programs