HashTable with Example


This class implements a hashtable, which maps keys to values. Any non-null object can be used as a key or as a value. To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method. An instance of Hashtable has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. Note that the hash table is open: in the case of a "hash collision", a single bucket stores multiple entries, which must be searched sequentially. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. The initial capacity and load factor parameters are merely hints to the implementation. The exact details as to when and whether the rehash method is invoked are implementation-dependent.


A hash table can only store objects that override the hashCode() and equals() methods that are defined by Object. The hashCode() method must compute and return the hash code for the object. Of course, equals() compares two objects. Fortunately, many of Java's built-in classes already implement the hashCode() method. For example, the most common type of Hashtable uses a String object as the key. String implements both hashCode() and equals().

Hash Table Example:

import java.util.*; 
class HTDemo2 { 
public static void main(String args[]) { 
Hashtable balance = new Hashtable(); 
String str; 
double bal; 
balance.put("John Doe", new Double(3434.34)); 
balance.put("Tom Smith", new Double(123.22)); 
balance.put("Jane Baker", new Double(1378.00)); 
balance.put("Todd Hall", new Double(99.22)); 
balance.put("Ralph Smith", new Double(-19.08)); 
// show all balances in hashtable 
Set set = balance.keySet(); // get set-view of keys 
// get iterator 
Iterator itr = set.iterator(); 
while(itr.hasNext()) { 
str = (String) itr.next(); 
System.out.println(str + ": " + 
balance.get(str)); 

System.out.println(); 
// Deposit 1,000 into John Doe's account 
bal = ((Double)balance.get("John Doe")).doubleValue(); 
balance.put("John Doe", new Double(bal+1000)); 
System.out.println("John Doe's new balance: " + 
balance.get("John Doe")); 

}
Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email


Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email