Java linkedlist size – Java LinkedList size() Method with Examples

Java linkedlist size: In the previous article, we have discussed about Java LinkedList set() Method with Examples

In this article we are going to see the use of Java LinkedList size() method along with suitable examples.

Java LinkedList size() Method with Examples

Java linked list size: This java.util.LinkedList.size() method is used to get the size of LinkedList means total number of elements present in the LinkedList.

It returns the size of the LinkedList

Syntax:

LinkedListName.size()

Where,

  • LinkedListName refers to the name of your LinkedList.

Let’s see different examples to understand it more clearly.

Example-1: Java LinkedList size() Method – Example with String Type LinkedList

Approach:

  • Create a new LinkedList of type String.
  • Add string elements into the LinkedList using the add() method.
  • Display the LinkedList elements.
  • Then find the size of the LinkedList using size() method.
  • Print the size of the LinkedList.

Program:

import java.util.*;
public class Main
{
    public static void main(String[] args)
    {
        // Create a LinkedList of string datatype
        LinkedList<String> l = new LinkedList<String>();
        // Adding some elements to the LinkedList
        l.add("c");
        l.add("c++");
        l.add("java");
        l.add("python");
        l.add("c#");
        // Prints the LinkedList elements
        System.out.println("The elements of LinkedList are: "+l);
        // Prints the size of the LinkedList
        System.out.println("The size of the LinkedList is: "+l.size());
    }
}

Output:

The elements of LinkedList are: [c, c++, java, python, c#]
The size of the LinkedList is: 5

Example-2: Java LinkedList size() Method – Example with Integer Type LinkedList

Approach:

  • Create a new LinkedList of type Integer.
  • Add Integer elements into the LinkedList using the add() method.
  • Display the LinkedList elements.
  • Then find the size of the LinkedList using size() method.
  • Print the size of the LinkedList.

Program:

import java.util.*;
public class Main
{
    public static void main(String[] args)
    {
        // Create a LinkedList of Integer datatype
        LinkedList<Integer> l = new LinkedList<Integer>();
        // Adding some elements to the LinkedList
        l.add(10);
        l.add(20);
        l.add(30);
        l.add(40);
        l.add(50);
        l.add(60);
        l.add(70);
        // Prints the LinkedList elements
        System.out.println("The elements of LinkedList are: "+l);
        // Prints the size of the LinkedList
        System.out.println("The size of the LinkedList is: "+l.size());
    }
}

Output:

The elements of LinkedList are: [10, 20, 30, 40, 50, 60, 70]
The size of the LinkedList is: 7

Interested in programming and want to excel in it by choosing the short ways. Then, practicing with the available Java Program list is mandatory.

Related Java Programs: