ArrayList all elements are null

Learn to check if ArrayList is empty or not using isEmpty[] and size[] methods. Please note that isEmpty[] method also internally check the size of arraylist.

1. Check if ArrayList is empty isEmpty[] example

ArrayList isEmpty[] method returns true if list contains no element. In other words, method returns true if list is empty. Else isEmpty[] method returns false.

In given example, we have first initialized a blank arraylist and checked if it is empty. Method returns true because there is nothing in the list. Then we added an element "A" to list and checked again. This time list is not empty and method returns false. Now we again cleared the list and checked again. List is empty again.

In application programming, it is advisable to check both if list is not null and then not empty. If list is not initialized, you may get NullPointerException in runtime.

public class ArrayListExample { public static void main[String[] args] { ArrayList list = new ArrayList[]; System.out.println[list.isEmpty[]]; //true list.add["A"]; System.out.println[list.isEmpty[]]; //false list.clear[]; System.out.println[list.isEmpty[]]; //true } }

Program output.

true false true

2. Check if ArrayList is empty size[] example

Another way to check if arraylist contains any element or not, we can check the size of arraylist. If the list size is greater than zero, then list is not empty. If list size is 0, list is empty.

If we look inside the isEmpty[] method, it also check the size of arraylist to determine if the list is empty or not.

public class ArrayListExample { public static void main[String[] args] { ArrayList list = new ArrayList[]; System.out.println[list.size[]]; //0 list.add["A"]; System.out.println[list.size[]]; //1 list.clear[]; System.out.println[list.size[] == 0]; //true } }

Program output.

0 1 true

Happy Learning !!

Read More:

A Guide to Java ArrayList
ArrayList Java Docs

Was this post helpful?

Let us know if you liked the post. Thats the only way we can improve.
Yes
No

Video liên quan

Chủ Đề