In this section, we will learn what the List size() method is and how to use it in Java.
What is Java List size() Method?
The size() method is used to return the current number of elements in a list object.
Note: we say the current number of elements! That means if you have a list object with 10 elements, for example, and call this method, you’ll get the value of 10. But then if you remove 4 elements of that list and call this method again, the return value will be 6 now.
Java List 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 equal to the current number of elements in the target object list and also this number is of type integer.
size() Method Exceptions:
This method does not throw an exception.
Example: using List size() method
import java.util.List; import java.util.ArrayList; public class Main { public static void main(String[] args){ List<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); 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 is: "+list.size()); } }
Output:
The size of the list before calling the clear method: 3 The size of the list is: 0
Here, as you can see, at first the target list had 3 elements, but then we’ve called the clear() method to clear all the elements of this list and as a result we got the value 0 when called the size() method again.