Java Hashtable isEmpty() Method
The Hashtable.isEmpty() method is a built-in method of the java.util.Hashtable class. This method is used to check if the table is empty or not. The method returns true, if no key-value pair or mapping is present in the table, else it returns false.
Syntax of Hashtable isEmpty() Method
hash_table.isEmpty();
- Parameters: The method does not take any parameters.
- Return Value: This method returns boolean true if the table is empty or does not contain any mapping pairs, else it returns false.
This method is used to check the state of the table before performing the operations like iteration, retrieval, or updates.
Examples of Java Hashtable isEmpty() Method
Example 1: In this example, we create a Hashtable with String keys and Integer values. Then we will insert multiple key-value pairs. After this, we will check if the table is empty using the isEmpty() method.
// Java program to demonstrate
// isEmpty() on an empty Hashtable
import java.util.Hashtable;
public class Geeks {
public static void main(String[] args)
{
// Creating an empty Hashtable
Hashtable<String, Integer> ht =
new Hashtable<String, Integer>();
// Inserting elements into the table
ht.put("Geeks", 10);
ht.put("4", 15);
ht.put("Geeks", 20);
ht.put("Welcomes", 25);
ht.put("You", 30);
System.out.println("The table is: " + ht);
// Checking for the emptiness of Table
System.out.println("Is the table empty? " +
ht.isEmpty());
}
}
Output
The table is: {You=30, Welcomes=25, 4=15, Geeks=20} Is the table empty? false
Example 2: In this example, we are going to create an empty Hashtable without adding any elements. In this case, the isEmpty() method will return true because the table has no key-value mappings.
// Java code to demonstrate isEmpty()
// on an empty Hashtable
import java.util.Hashtable;
public class Geeks {
public static void main(String[] args)
{
// Creating an empty Hashtable
Hashtable<String, Integer> ht = new Hashtable<String, Integer>();
System.out.println("The table is: " + ht);
// Checking for the emptiness of Table
System.out.println("Is the table empty? " + ht.isEmpty());
}
}
Output
The table is: {} Is the table empty? true
Note: The same operation can be performed with any type of variation and combination of different data types.