Java Hashtable toString() Example

The toString() method of java.util.Hashtable class will returns a string representation of this Hashtable object in the form of a set of entries, enclosed in braces and separated by comma and space.

Signature

public String toString()

This method returns a string representation of this Hashtable object in the form of a set of entries, enclosed in braces and separated by comma and space. Each entry is rendered as the key, an equals sign =, and the associated element.

Example

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

import java.util.Hashtable;

public class ToStringMethodHashtableExample 
{
    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 Hashtable
        hashtable1.put(1,"Element1");
        hashtable1.put(2,"Element2");
        hashtable1.put(4,"Element4");
        hashtable1.put(5,"Element5");
        hashtable1.put(3,"Element3");
        
        //Use toString print hashtable key value pairs
        System.out.println("**Elements of \"hashtable1\"**");
        System.out.println(hashtable1.toString());
    }
}

Output

**Elements of "hashtable1"**
{5=Element5, 4=Element4, 3=Element3, 2=Element2, 1=Element1}

Leave a Reply

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