Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

hashtable
java
communitycreator

How to use Hashtable.containsKey method in Java?

Programming Bytes

What is a HashTable?

A HashTable is a collection of key-value pairs. The Object used as a key should implement the hashCode and equals method. The key and the value should not be null.


You can read about the difference between HashTable and HashMap here.

What is the containsKey() method in Hashtable?

The containsKey() method of Hashtable is used to check if a value is mapped to the specified key.

Syntax


public boolean containsKey(Object key)

Argument

The key to being checked for presence is passed as an argument.


If we pass null as an argument, then the NullPointerException is thrown.

Return value

This method returns true if the key has a mapping. Otherwise, false is returned.

Code

The example below shows how to use the containsKey() method.

import java.util.Hashtable;
class HashtableContainsKeyExample {
    public static void main( String args[] ) {
      Hashtable<Integer, String> map = new Hashtable<>();
      map.put(1, "one");
      map.put(2, "two");
      System.out.println("Checking if the key '1' has mapping: "+ map.containsKey(1));
      System.out.println("Checking if the key '3' has mapping: "+ map.containsKey(3));
    }
}

Explanation

In the above code:

  • In line 1, we import the Hashtable class.

  • In line 2, we create a Hashtable object with the name map.

  • In line 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 containsKey method to check if the map has a mapping for the key 1. true is returned as a result because the map has a mapping for the key 1.

  • In line 8, we use the containsKey method to check if the map has a mapping for the key 3. false is returned as a result because the map has a mapping for the key 3.

RELATED TAGS

hashtable
java
communitycreator
RELATED COURSES

View all Courses

Keep Exploring