This example shows how to get the Hashtable size (Hashtable length) using the size method. The Hashtable size is the number of entries contained in the hash table object.
How to get the Hashtable size in Java?
The Hashtable size
method returns the number of entries or key-value mappings stored in the hash table object.
1 |
public int size() |
It returns the number of keys in the hash table object. It returns zero (0) if the hash table is empty.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import java.util.Hashtable; public class HashtableSizeExample { public static void main(String[] args) { Hashtable<Integer, String> hashtable = new Hashtable<Integer, String>(); /* * To get the number of entries * contained in the hashtable, use the * size method */ //this will return 0 as there are no entries System.out.println( "Size is: " + hashtable.size() ); //add some entries hashtable.put(1, "One"); hashtable.put(2, "Two"); //this will now return 2 as there are two entries System.out.println( "Size is: " + hashtable.size() ); } } |
Output
1 2 |
Size is: 0 Size is: 2 |
How to check if the Hashtable is empty using the size method?
The Hashtable size
method returns 0 if the hashtable is empty. We can compare the return value of the size
method with zero (0) to check if the hash table is empty or not as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.util.Hashtable; public class HashtableSizeExample { public static void main(String[] args) { Hashtable<Integer, String> hashtable = new Hashtable<Integer, String>(); //this will return true as the hashtable is empty System.out.println( "Is empty: " + (hashtable.size() == 0) ); //add some entries hashtable.put(1, "One"); hashtable.put(2, "Two"); //this will now return false as there are two entries System.out.println( "Is empty: " + (hashtable.size() == 0) ); } } |
Output
1 2 |
Is empty: true Is empty: false |
This example is a part of the Hashtable in Java Tutorial with Examples.
Please let me know your views in the comments section below.
References:
Java 8 Hashtable Documentation