How is HashTable.contains used in Java?
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.
# Syntax
public boolean contains(Object value)
Argument
The value to be checked for presence is passed as an argument.
Return value
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.
Code
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"));}}
Explanation
In the code above:
-
In line 1, we import the
Hashtableclass. -
In line 4, we create a
Hashtableobject with the namemap. -
In lines 5 and 6, we use the
putmethod to add two mappings ({1=one, 2=two}) to themapobject. -
In line 7, we use the
containsmethod to check if themaphas a key mapping for the value"one".trueis returned as a result because the key1is mapped to the value"one". -
In line 8, we use the
containsmethod to check if themaphas a key mapping for the value"three".falseis returned as a result because no key is mapped for the value"three".