What is the HashTable.contains() method in Java?
The HashTable.contains() method is present in the HashTable class inside the java.util package.
It is used to check whether or not a particular value is being mapped by any keys present in the HashTable.
Syntax
HashTable.contains(Object value)
Parameters
HashTable.contains() takes one parameter.
value: The value of the hashtable whose mapping is to be verified.
Return value
HashTable.contains() returns a boolean value.
-
true: If the value passed as an argument is being mapped by any keys present in theHashTable. -
false: If the value passed as argument is not being mapped by any keys present in theHashTable.
Example
Let’s go over this with the help of an example.
Suppose we have the following HashTable:
{
1 = "Let's",
5 = "see",
2 = "HashTable.contains()",
27 = "method"
}
When we use HashTable.contains(), the method returns true if any of the values present in HashTable are parameterized inside HashTable.contains().
Otherwise, it returns false.
Code
Let’s look at the below code snippet to better understand this.
import java.util.*;class Main{public static void main(String[] args){Hashtable<Integer, String> h1 = new Hashtable<Integer, String>();h1.put(1, "Let's");h1.put(5, "see");h1.put(2, "Hashtable.contains()");h1.put(27, "method");h1.put(9, "in java.");System.out.println("The Hashtable is: " + h1);System.out.println("Is \"HashTable.contains()\" being mapped by any of the keys in the HashTable: " + h1.contains("HashTable.contains()"));System.out.println("Is \"in java. being mapped\" by any of the keys in the HashTable: " + h1.contains("in java."));System.out.println("Is \"value being mapped\" by any of the keys in the HashTable: " + h1.contains("value"));}}
Explanation
- In line 1, we import the required package.
- In line 2, we make a
Mainclass. - In line 4, we make a
mainfunction. - In line 6, we declare a
Hashtableconsisting ofIntegertype keys andStringtype values. - In lines 8 to 12, we insert values in the
HashTableby using theHashtable.put()method. - In line 14, we display the original
HashTable. - In line 15 to 17, we check for the particular values that are either being mapped or not being mapped in the
HashTablewith the result and a message.
In this way, we can use the HashTable.contains() method to check whether or not a particular value is being mapped by any keys present in the HashTable.