Java 9 ArrayList clear and empty check

You can check if an ArrayList list is empty by method: isEmpty() and clear list by method: clear(). Alternatively you can clear ArrayList element by element. in this post:

  • Test ArrayList is empty
  • Clear ArrayList in Java
  • Clear ArrayList element by element

You can check also:

Test ArrayList is empty

If you need easy and standard way to check if ArrayList is empty you can do it by: isEmpty() which return boolean result:

  • false - not empty
  • true - empty
import java.util.ArrayList;

ArrayList<String> mylist = new ArrayList<>();
System.out.println(mylist.isEmpty());

mylist.add("Java");

System.out.println(mylist.isEmpty());

result:

true
false

Clear ArrayList in Java

Removing all elements from ArrayList can be done by clear method:

import java.util.ArrayList;

ArrayList<String> mylist = new ArrayList<>();
mylist.add("Java");
mylist.clear();
System.out.println(mylist.isEmpty());

result:

true

Clear ArrayList element by element

Sometimes you may need to perform action to elements before deleting them. This can be done by removing element by element:

import java.util.ArrayList;

ArrayList<String> cars = new ArrayList<>();
cars.add("BMW");
cars.add("KIA");
cars.add("VOLVO");
cars.add("OPEL");

while(!cars.isEmpty()){
    cars.remove(0);
}

System.out.println(cars.isEmpty());

result:

true