The isEmpty() of java.util.Collection interface is used to check if the Collection upon which it is called is empty or not. This method does not take any parameter and does not returns any value.
Syntax:
Collection.isEmpty()
Parameters: This method do not accept any parameter
Return Value: This method does not return any value.
Below examples illustrate the Collection isEmpty() method:
Example 1: Using LinkedList Class
import java.io.*;
import java.util.*;
public class GFG {
public static void main(String args[])
{
Collection<String> list = new LinkedList<String>();
list.add( "Geeks" );
list.add( "for" );
list.add( "Geeks" );
System.out.println( "The list is: " + list);
System.out.println( "Is the LinkedList empty: "
+ list.isEmpty());
list.clear();
System.out.println( "The new List is: " + list);
System.out.println( "Is the LinkedList empty: "
+ list.isEmpty());
}
}
|
Output:
The list is: [Geeks, for, Geeks]
Is the LinkedList empty: false
The new List is: []
Is the LinkedList empty: true
Example 2: Using ArrayDeque Class
import java.util.*;
public class ArrayDequeDemo {
public static void main(String args[])
{
Collection<String> de_que = new ArrayDeque<String>();
de_que.add( "Welcome" );
de_que.add( "To" );
de_que.add( "Geeks" );
de_que.add( "4" );
de_que.add( "Geeks" );
System.out.println( "ArrayDeque: " + de_que);
System.out.println( "Is the ArrayDeque empty: "
+ de_que.isEmpty());
de_que.clear();
System.out.println( "The new ArrayDeque is: "
+ de_que);
System.out.println( "Is the ArrayDeque empty: "
+ de_que.isEmpty());
}
}
|
Output:
ArrayDeque: [Welcome, To, Geeks, 4, Geeks]
Is the ArrayDeque empty: false
The new ArrayDeque is: []
Is the ArrayDeque empty: true
Example 3: Using ArrayList Class
import java.io.*;
import java.util.*;
public class ArrayListDemo {
public static void main(String[] args)
{
Collection<Integer>
arrlist = new ArrayList<Integer>( 5 );
arrlist.add( 15 );
arrlist.add( 20 );
arrlist.add( 25 );
System.out.println( "ArrayList: " + arrlist);
System.out.println( "Is the ArrayList empty: "
+ arrlist.isEmpty());
arrlist.clear();
System.out.println( "The new ArrayList is: "
+ arrlist);
System.out.println( "Is the ArrayList empty: "
+ arrlist.isEmpty());
}
}
|
Output:
ArrayList: [15, 20, 25]
Is the ArrayList empty: false
The new ArrayList is: []
Is the ArrayList empty: true
Reference: https://docs.oracle.com/javase/9/docs/api/java/util/Collection.html#isEmpty–
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
29 Nov, 2018
Like Article
Save Article