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 the HashTable.

  • false: If the value passed as argument is not being mapped by any keys present in the HashTable.

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 Main class.
  • In line 4, we make a main function.
  • In line 6, we declare a Hashtable consisting of Integer type keys and String type values.
  • In lines 8 to 12, we insert values in the HashTable by using the Hashtable.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 HashTable with 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.

Free Resources