w3resource

Java: Test an array list is empty or not


Write a Java program to test whether an array list is empty or not.

Pictorial Presentation:

Java Collection, ArrayList Exercises: Test an array list is empty or not.

Sample Solution:-

Java Code:

import java.util.ArrayList;
import java.util.Collections;
  public class Exercise18 {
  public static void main(String[] args) {
          ArrayList<String> c1= new ArrayList<String>();
          c1.add("Red");
          c1.add("Green");
          c1.add("Black");
          c1.add("White");
          c1.add("Pink");
          System.out.println("Original array list: " + c1);
          System.out.println("Checking the above array list is empty or not! "+c1.isEmpty());
          c1.removeAll(c1);
          System.out.println("Array list after remove all elements "+c1);   
          System.out.println("Checking the above array list is empty or not! "+c1.isEmpty());
   }
}

Sample Output:

Original array list: [Red, Green, Black, White, Pink]                  
Checking the above array list is empty or not! false                   
Array list after remove all elements []                                
Checking the above array list is empty or not! true 

Flowchart:

Flowchart: Test an array list is empty or not.

For more Practice: Solve these Related Problems:

  • Write a Java program to check if an ArrayList is empty using the isEmpty() method and print a custom message.
  • Write a Java program to use a lambda expression with allMatch() to test if an ArrayList contains no elements.
  • Write a Java program to iterate over an ArrayList and determine emptiness by counting elements manually.
  • Write a Java program to compare two ArrayLists and determine if one is empty while the other is not.

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Empty an array list.
Next: Trim the capacity of an array list the current list size.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.