Verify List Size with size()
In the previous step, we learned how to check if a list is empty using isEmpty()
. While isEmpty()
is great for checking if a list has any elements, sometimes you need to know exactly how many elements are in a list. For this, Java provides the size()
method.
In this step, we will modify our ListCheck.java
file to use the size()
method and see how it works.
Open the ListCheck.java
file in the WebIDE editor if it's not already open. It should be located in your ~/project
directory.
Now, let's add some lines to our main
method to print the size of our lists. Add the following lines after the lines where you used isEmpty()
:
import java.util.ArrayList;
import java.util.List;
public class ListCheck {
public static void main(String[] args) {
// Create an empty list
List<String> emptyList = new ArrayList<>();
// Create a list with elements
List<String> populatedList = new ArrayList<>();
populatedList.add("Apple");
populatedList.add("Banana");
// Check if the lists are empty using isEmpty()
System.out.println("Is emptyList empty? " + emptyList.isEmpty());
System.out.println("Is populatedList empty? " + populatedList.isEmpty());
// Get and print the size of the lists using size()
System.out.println("Size of emptyList: " + emptyList.size());
System.out.println("Size of populatedList: " + populatedList.size());
}
}
We added two new lines:
System.out.println("Size of emptyList: " + emptyList.size());
: This line calls the size()
method on emptyList
. The size()
method returns the number of elements in the list as an integer.
System.out.println("Size of populatedList: " + populatedList.size());
: This line does the same for populatedList
.
Save the ListCheck.java
file.
Now, go back to the Terminal in the ~/project
directory. We need to recompile the modified Java code:
javac ListCheck.java
If the compilation is successful, run the program again:
java ListCheck
You should now see output similar to this:
Is emptyList empty? true
Is populatedList empty? false
Size of emptyList: 0
Size of populatedList: 2
As you can see, size()
correctly reported that emptyList
has 0 elements and populatedList
has 2 elements.
While you could check if a list is empty by checking if its size is 0 (list.size() == 0
), using isEmpty()
is generally preferred for clarity and readability. However, size()
is essential when you need to know the exact number of elements in a list, for example, when looping through the list or performing calculations based on the number of items.