Java Hashtable containsKey(Object key) Method Example

The containsKey(Object key) method of java.util.Hashtable class returns true if this set contains a mapping for the specified key.

Signature

public boolean containsKey(Object key)

This method returns true if this set contains a mapping for the specified key.

Example

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

import java.util.Hashtable;

public class ContainsKeyMethodHashtableExample 
{
    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");
        
        //Check if the hashtable1 contains key "2"
        System.out.println("Does \"hashtable1\" contains key \"2\" : "+hashtable1.containsKey(2));
    }
}

Output

Does "hashtable1" contains key "2" : true

Leave a Reply

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