Java LinkedList size() Method Tutorial

In this section, we will learn what the LinkedList size() method is and how to use it in Java.

What is Java LinkedList size() Method?

The Java LinkedList size() method is used to get the current number of elements in a LinkedList object.

Java size() Method Syntax:

public int size()

size() Method Parameters:

The method does not take an argument.

size() Method Return Value:

The return value of this method is the current number of elements in the target LinkedList object.

size() Method Exceptions:

The method does not throw an exception.

Example: using LinkedList size() method

import java.util.LinkedList;
class Main{
    public static void main(String[] args) {
        LinkedList<String> list = new LinkedList<>();
        list.add("John");
        list.add("Omid");
        list.add("Jack");
        list.add("Ellen");
        list.add("Barack");
        list.add("Ian");
        list.add("Paul");
        
        System.out.println("The size of the list before calling the clear method: "+ list.size());
        list.clear();
        System.out.println("The size of the list after calling the clear method: "+list.size());
    }
}

Output:

The size of the list before calling the clear method: 7

The size of the list after calling the clear method: 0

Leave a Reply