A HashTable is a collection of key-value pairs. The object to be used as a key should implement the hashCode and equals method, and the key and the value should not be null.
You can read more about the difference between
HashTableandHashMaphere.
The contains method of Hashtable is used to check if a specified value is present in the Hashtable object.
public boolean contains(Object value)
The value to be checked for presence is passed as an argument.
This method throws NullPointerException if the argument is null.
This method returns true if the value has one or more keys mapping. Otherwise, false is returned.
The below example shows how to use the contains method.
import java.util.Hashtable;class HashtableContainsExample {public static void main( String args[] ) {Hashtable<Integer, String> map = new Hashtable<>();map.put(1, "one");map.put(2, "two");System.out.println("\nChecking if the value 'one' is present : "+ map.contains("one"));System.out.println("\nChecking if the value 'three' is present : "+ map.contains("three"));}}
In the code above:
In line 1, we import the Hashtable class.
In line 4, we create a Hashtable object with the name map.
In lines 5 and 6, we use the put method to add two mappings ({1=one, 2=two}) to the map object.
In line 7, we use the contains method to check if the map has a key mapping for the value "one". true is returned as a result because the key 1 is mapped to the value "one".
In line 8, we use the contains method to check if the map has a key mapping for the value "three". false is returned as a result because no key is mapped for the value "three".