The size() and isEmpty() of java.util.Collection interface is used to check the size of collections and if the Collection is empty or not. isEmpty() method does not take any parameter and does not return any value.
Example:
Input:[99, 54, 112, 184, 2]
Output:size = 5 and Collection is not empty
Input:[]
Output: size = 0 and Collection is empty
size() method:
Syntax:
public int size()
Parameters: This method does not takes any parameters.
Return Value: This method returns the number of elements in this list.
isEmpty() method:
Syntax:
Collection.isEmpty()
Parameters: This method do not accept any parameter
Return Value: This method does not return any value.
Example 1: Using LinkedList Class
Java
import java.io.*;
import java.util.*;
class GFG {
public static void main (String[] args) {
Collection<Integer> list = new LinkedList<Integer>();
list.add( 99 );
list.add( 54 );
list.add( 112 );
list.add( 184 );
list.add( 2 );
System.out.print( "The elements in Collection : " );
System.out.println(list);
System.out.println( "Size of the collection " +list.size());
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 elements in Collection : [99, 54, 112, 184, 2]
Size of the collection 5
Is the LinkedList empty: false
The new List is: []
Is the LinkedList empty: true
Example 2: Using ArrayList Class
Java
import java.io.*;
import java.util.*;
class GFG {
public static void main (String[] args) {
Collection<String> arraylist = new ArrayList<String>();
arraylist.add( "Geeks" );
arraylist.add( "for" );
arraylist.add( "geeks" );
System.out.println( "Size of the collection " +arraylist.size());
System.out.println( "Is the ArrayList empty: "
+ arraylist.isEmpty());
}
}
|
Output
Size of the collection 3
Is the ArrayList empty: false
Feeling lost in the vast world of Backend Development? It's time for a change! Join our
Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
- Comprehensive Course
- Expert Guidance for Efficient Learning
- Hands-on Experience with Real-world Projects
- Proven Track Record with 100,000+ Successful Geeks
Last Updated :
07 Jan, 2021
Like Article
Save Article