Java List size() example

In this guide, you will learn about the List size() method in Java programming and how to use it with an example.

1. List size() Method Overview

Definition:

The size() method of the Java List interface is used to get the number of elements present in the list. It provides a quick way to determine the length or size of a list.

Syntax:

int size = list.size();

Parameters:

None.

Key Points:

- The size() method returns the count of elements present in the list.

- If the list is empty, the method returns 0.

- The returned size can be useful for loop-based operations on a list, among other things.

2. List size() Method Example

import java.util.ArrayList;
import java.util.List;

public class ListSizeExample {
    public static void main(String[] args) {
        // Create an empty ArrayList
        List<String> animals = new ArrayList<>();
        System.out.println("Size of empty list: " + animals.size()); // Outputs: 0

        // Add some elements to the list
        animals.add("Cat");
        animals.add("Dog");
        animals.add("Elephant");
        System.out.println("Size after adding elements: " + animals.size()); // Outputs: 3

        // Remove an element from the list
        animals.remove(1); // removing "Dog"
        System.out.println("Size after removing an element: " + animals.size()); // Outputs: 2

        // Iterating over the list using size() for boundary
        for (int i = 0; i < animals.size(); i++) {
            System.out.println(animals.get(i));
        }
    }
}

Output:

Size of empty list: 0
Size after adding elements: 3
Size after removing an element: 2
Cat
Elephant

Explanation:

In this example:

1. We start with an empty ArrayList named animals.

2. We first check the size of the empty list, which is, unsurprisingly, 0.

3. We then add three animal names to the list and check its size, which now reflects the added elements and returns 3.

4. After removing an element ("Dog") from the list, the size is updated to 2.

5. Finally, we iterate through the list using a for loop, using the size() method to set our boundary for iteration.

The size() method is fundamental when working with lists in Java, allowing for dynamic size checking, especially useful when you add or remove elements and need to know the current size.

Related Java List methods

Java List add() example
Java List clear() example
Java List contains() example
Java List get() example
Java List indexOf() example
Java List remove() example
Java List size() example
Java List toArray() example

Comments