Java Hashtable put(K key, V value) Example

The put(K key, V value) method of java.util.Hashtable class Maps the specified key to the specified value in this hashtable. Neither the key nor the value can be null.

Signature

public V put(K key, V value)

This method Maps the specified key to the specified value in this hashtable. Neither the key nor the value can be null. The value can be retrieved by calling the get method with a key that is equal to the original key.

Example

The following example shows the usage of java.util.Hashtable.put(key,value) method.

package com.javainterviewpoint;

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

public class PutMethodHashtableExample
{
    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(3,"Element3");
        hashtable1.put(4,"Element4");
        hashtable1.put(5,"Element5");
        
        //Printing the elements of the hashtable1
        System.out.println("**Elements of hashtable1**");
        for(Map.Entry<Integer,String> entry : hashtable1.entrySet())
        {
            System.out.println("Key : "+entry.getKey()+" Value : "+entry.getValue());
        }
    }
}

Output

**Elements of hashtable1**
Key : 5 Value : Element5
Key : 4 Value : Element4
Key : 3 Value : Element3
Key : 2 Value : Element2
Key : 1 Value : Element1

Leave a Reply

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