Learn to check if ArrayList is empty or not using
size() methods. Please note that
isEmpty() method also internally check the size of ArrayList.
1. Using ArrayList.isEmpty()
The ArrayList.isEmpty() method returns true if the list contains no elements. In other words, the method returns true if the list is empty. Else isEmpty() method returns false.
public boolean isEmpty();
In the given example, we first initialized an empty ArrayList and checked if it was empty. Method returns
true because there is nothing inside the list.
ArrayList<String > list = new ArrayList(); Assertions.assertTrue(list.isEmpty());
Then we added an element
"A" to list and check again. This time list is not empty, and the method returns false. Now we again cleared the list and checked again. The list is empty again.
list.add("1"); Assertions.assertFalse(list.isEmpty()); list.clear(); Assertions.assertTrue(list.isEmpty());
In application programming, it is advisable to check both if list is not null and then not empty. If list is not initialized, we may get NullPointerException in runtime.
2. Using ArrayList.size()
Another way to check if the arraylist contains any element or not, we can check the size of the arraylist. If the list size is greater than zero, then the list is not empty. If the list size is 0, the list is empty.
If we look inside the isEmpty() method, it also checks the size of the arraylist to determine if it is empty.
ArrayList<String > list = new ArrayList(); Assertions.assertTrue(list.size() == 0); list.add("1"); Assertions.assertTrue(list.size() == 1); list.clear(); Assertions.assertTrue(list.size() == 0);
Happy Learning !!
Read More: ArrayList Java Docs