CodesJava

Easy learning with example program codes

how to search a key in hashtable?


Hashtable:

Hashtable extends Dictionary class and implements Map interface. It contains elements in key-value pair. It not allowed duplicate key. It is synchronized. It can’t contain null key or value. It uses hashcode() method for finding the position of the elements.

We can use containsKey() method to search a key in hashtable.

Example:

package com.codesjava;
 
import java.util.Hashtable;
 
public class Test {
  public static void main(String args[]){
	//Create Hashtable object.
	Hashtable<String, String> hashtable = new Hashtable<String, String>();
	//Add objects to the Hashtable.
	hashtable.put("1", "Jai");
	hashtable.put("2", "Mahesh");
	hashtable.put("3","Vivek");
        System.out.println(hashtable);
        if(hashtable.containsKey("2")){
            System.out.println("The Hashtable contains key 2");
        } else {
            System.out.println("The Hashtable does not contains key 2");
        }
  }
}

Output

{3=Vivek, 2=Mahesh, 1=Jai}
The Hashtable contains key 2
Sign Up/ Sign In
Ask a Question


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki