What is the LinkedList.size method in Java?

What is LinkedList?

A linked list is a collection of linear data elements. Each element (node) contains data and reference parts. The data part has the value and the reference part has the address to the next element.

The elements are not indexed so random access is not possible. Instead, we traverse from the beginning of the list and access the elements.

In Java, the LinkedList is a doubly-linked listKind of linked list. Each node contains three fields: two link fields(one for the previous element and another for the next element) and one data field. implementation of the List and Deque interfaces. The LinkedList is class present in the java.util package.

What is the size method of the LinkedList class?

The size method can be used to get the sizeNumber of elements present in the list of the linked list.

Syntax

public int size()

This method doesn’t take in any arguments. It returns the number of elements present in the list as an integer.

Code

The code below demonstrates how to use the size method.

import java.util.LinkedList;
class LinkedListSize {
public static void main( String args[] ) {
LinkedList<String> list = new LinkedList<>();
list.add("1");
list.add("2");
list.add("3");
System.out.println("The list is " + list);
System.out.println("The size of list is : " + list.size());
}
}

Explanation

In the code above:

  • In line 1, we imported the LinkedList class.
import java.util.LinkedList;
  • In line 4, we created a LinkedList object with the name list.
LinkedList<String> list = new LinkedList<>();
  • In lines 5 to 7, we used the add method of the list object to add three elements ("1","2","3") to the list.
list.add("1");
list.add("2");
list.add("3");
  • In line 10, we used the size method of the list object to get the size of the list. In our case, 3 will be returned because the list object has 3 elements.
list.size(); // 3

Free Resources