Java Hashtable size() Example

The size() method of java.util.Hashtable class will returns the number of key-value mappings in this map.

Signature

public int size()

This method returns the number of key-value mappings in this map.

Example

The following example shows the usage of java.util.Hashtable.size() method.

import java.util.Hashtable;
import java.util.Map;

public class RemoveMethodHashtableExample 
{
    public static void main(String args[])
    {
        // create an empty Hashtable
        Hashtable<Integer,String> hashtable1 = new Hashtable<Integer,String>();
        
        // use put() method to put elements to the Hashtable1
        hashtable1.put(1,"Element1");
        hashtable1.put(2,"Element2");
        hashtable1.put(3,"Element3");
        hashtable1.put(4,"Element4");
        hashtable1.put(5,"Element5");
        
        //Lets print the size of the hashtable
        System.out.println("**Size of the hashtable is : \""+hashtable1.size()+"\"**");
        System.out.println("**Elements of hashtable1 before remove()**");
        
        //Print the elements of hashtable1
        for (Map.Entry<Integer,String> entry : hashtable1.entrySet())
        {
            System.out.println("Key : "+entry.getKey()+" Value : "+entry.getValue());
        }
        
        //lets remove the value associated to key "3"
        System.out.println("Element removed : \""+hashtable1.remove(3)+"\"");
        System.out.println("**Size of the hashtable is : \""+hashtable1.size()+"\"**");
        System.out.println("**Elements of hashtable1 after remove()**");
        //Print the elements of hashtable1
        for (Map.Entry<Integer,String> entry : hashtable1.entrySet())
        {
            System.out.println("Key : "+entry.getKey()+" Value : "+entry.getValue());
        }
    }
}

Output

**Size of the hashtable is :"5"**
**Elements of hashtable1 before remove()**
Key : 1 Value : Element1
Key : 2 Value : Element2
Key : 3 Value : Element3
Key : 4 Value : Element4
Key : 5 Value : Element5
Element removed : "Element3"
**Size of the hashtable is :"4"**
**Elements of hashtable1 after remove()**
Key : 1 Value : Element1
Key : 2 Value : Element2
Key : 4 Value : Element4
Key : 5 Value : Element5

Leave a Reply

Your email address will not be published. Required fields are marked *