Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
java

What is the HashTable.containsKey() method in Java?

Sumit Sharma

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

In this shot, we will discuss how to use the HashTable.containsKey() method in Java.

The HashTable.containsKey() method is present in the HashTable class inside the java.util package.

The HashTable.containsKey() method is used to check whether a particular key is present in the HashTable or not.

Syntax

HashTable.containsKey(Key)

Parameter

The HashTable.containsKey() method takes one parameter.

  • Key: The key whose presence needs to be checked in the HashTable.

Return value

This method returns a Boolean value.

  • True: If the key is present in the HashTable.

  • False: If the key is not present in the HashTable.

Code

Let’s look at the code snippet below to understand it better.

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 key=5 is present in Hashtable?: "+h1.containsKey(5));
System.out.println("The key=9 is present in Hashtable?: "+h1.containsKey(9));
System.out.println("The key=14 is present in Hashtable?: "+h1.containsKey(14));
System.out.println();
}
}
Using HashTable.containsKey() method in Java

Explanation

  • In line 1, we imported the required package.

  • In line 2, we made a Main class.

  • In line 4, we made a main function.

  • In line 6, we declared a Hashtable consisting of Integer type keys and String type values.

  • In lines 8 to 12, we inserted values in the Hashtable by using the Hashtable.put() method.

  • In lines 14 to 16, we display whether the key passed as argument is present in the HashTable or not with a message.

In this way, we can use HashTable.containsKey() to check whether the particular key is present in the HashTable or not.

RELATED TAGS

communitycreator
java

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring