In Java, the List
interface is a part of the Java Collections Framework and is commonly used to store ordered collections of elements. One of the most frequently used methods in the List
interface is the size()
method. This method returns the number of elements present in the list. Knowing the size of a list is important for various operations like traversing, conditional logic, and resizing data structures.
In this article, we’ll explain the size()
method, its syntax, and provide examples of how to use it in different scenarios.
What is the size() Method in Java?
The size()
method is a part of the java.util.List
interface. It returns an int
value representing the number of elements in the list. The method does not take any arguments and operates in constant time, making it an efficient way to obtain the length of a list.
Syntax:
Key Points:
- The
size()
method is non-negative and will return a value greater than or equal to0
. - It returns the current number of elements, not the maximum capacity.
- The method is typically used to check if a list is empty or to loop through a list by indexing.
Example 1: Using size() to Get the Number of Elements in a List
Here’s an example demonstrating the use of the size()
method to get the number of elements in a List
.
Output:
In this example, the size()
method returns 3
because three elements have been added to the list.
Example 2: Checking If a List is Empty Using size()
You can use the size()
method to check if a list is empty. A list is considered empty if its size is zero.
Output:
In this case, since no elements were added to the colors
list, the size()
method returns 0
, and the program prints that the list is empty.
Example 3: Using size() to Loop Through a List
The size()
method is commonly used in loops to iterate over a list. Here’s an example of using size()
to loop through a list of integers.
Output:
In this example, the size()
method is used to determine the loop’s upper bound. The loop iterates through each element of the list by index.
Example 4: Dynamically Changing the List Size
The size of a list can change as elements are added or removed. The size()
method reflects these changes in real time. Let’s look at an example of adding and removing elements and how it affects the size of the list.
Output:
In this case, the list initially contains three elements. After removing one element, the size()
method reflects the updated size.
The size()
method in Java is a simple yet powerful tool for working with lists. It allows you to determine the number of elements in a list, check if it’s empty, and manage iterations. Understanding how to use size()
is fundamental when working with the List
interface, as it provides valuable insight into the contents of a collection.
Whether you’re managing dynamic collections or performing operations based on the number of elements, the size()
method is a key part of Java’s collection framework.