Java Hashtable contains(Object o) Example

The contains(Object o) method of java.util.Hashtable class will test if some key maps into the specified value in this hashtable. This operation is more expensive than the containsKey method.

Signature

public boolean contains(Object o)

This method test if some key maps into the specified value in this hashtable. This operation is more expensive than the containsKey method.

Example

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

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

public class ContainsMethodHashtableExample 
{
    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 the hashtable1**");
        for(Map.Entry<Integer,String> mapEntry : hashtable1.entrySet())
        {
            System.out.println("Key : "+mapEntry.getKey()+" Value : "+mapEntry.getValue());
        }
        
        //Lets check if the hashtable1 has "Element2"
        System.out.println("Does hashtable1 has \"Element2\" : "+hashtable1.contains("Element2"));
    }
}

Output

**Elements of the hashtable1**
Key : 5 Value : Element5
Key : 4 Value : Element4
Key : 3 Value : Element3
Key : 2 Value : Element2
Key : 1 Value : Element1
Does hashtable1 has "Element2" : true

Leave a Reply

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