The Java.util.LinkedList.size() method is used to get the size of the Linked list or the number of elements present in the linked list.
Syntax:
LinkedList.size()
Parameters: This method does not take any parameter.
Return Value: This method returns the size or the number of elements present in the LinkedList.
Below program illustrates the Java.util.LinkedList.size() method:
Example 1:
Java
// Java code to illustrate size() method // of LinkedList class import java.io.*; import java.util.LinkedList; public class LinkedListDemo { public static void main(String args[]) { // Creating an empty LinkedList LinkedList<String> list = new LinkedList<String>(); // Using add() method to add elements in the list list.add( "Geeks" ); list.add( "for" ); list.add( "Geeks" ); list.add( "10" ); list.add( "20" ); // Displaying the linkedlist System.out.println( "LinkedList:" + list); // Displaying the size of the list System.out.println( "The size of the linked list is: " + list.size()); } } |
In Java, the LinkedList class provides the size() method to get the number of elements in the list. The method returns an integer representing the number of elements in the list.
Example 2:
Java
import java.util.LinkedList; public class Example { public static void main(String[] args) { LinkedList<String> list = new LinkedList<>(); // Adding elements to the list // using add() method list.add( "apple" ); list.add( "banana" ); list.add( "orange" ); list.add( "grape" ); System.out.println( "Original list:" ); System.out.println(list); // get the size of the list int size = list.size(); System.out.println( "Size of list: " + size); } } |
Original list: [apple, banana, orange, grape] Size of list: 4
In this example, we first create a LinkedList object and add four elements to it. The System.out.println() statement prints the original list to the console.
We then use the size() method to get the number of elements in the list, and print the size to the console.