The Hashtable Class

In this section, you will learn about Hashtable and its implementation with the help of example.

The Hashtable Class

In this section, you will learn about Hashtable and its implementation with the help of example.

Hashtable is integrated with the collection framework and also implements the Map interface. Similar to HashMap it also stores key/value pair in Hashtable. But the difference is Hashtable is synchronized.

Hashtable supports 4 types of constructor :

(1) The first constructor is the default constructor. It's syntax is:


(2) The second constructor provide freedom to user to define initial size of the Hashtable. Syntax is below :

Hashtable(int size)

(3) In third constructor, user can define its initial size and and a fill ratio specified by load factor.

Hashtable(int size, float load factor)

The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. It's value must lie in between 0.0 and 1.0.

(4) In fourth Hashtable, user can pass a Map as argument. It provide the same mapping as in the provided Map but the capacity of the hash table is twice the number of elements in the passed Map. Syntax is provided below :

Hashtable(Map m)

It also has its own method. In spite of that , it also supports Map interface methods. Click here for complete list of Hashtable's method.


import java.util.*;

public class HashTableExample {
public static void main(String args[]) {
// Create a hash map
Hashtable ht = new Hashtable();
Enumeration htenum;
String str;
double bal;

ht.put("Neha", new Double(3434.34));
ht.put("Ankit", new Double(123.22));
ht.put("Rohit", new Double(1378.00));
ht.put("Vinay", new Double(99.22));
ht.put("Vijay", new Double(-19.08));

// Show all balances in hash table.
htenum = ht.keys();
while (htenum.hasMoreElements()) {
str = (String) htenum.nextElement();
System.out.println(str + ": " + ht.get(str));
// Deposit 1,000 into Neha's account
bal = ((Double) ht.get("Neha")).doubleValue();
ht.put("Neha", new Double(bal + 1000));
System.out.println("Neha's new balance: " + ht.get("Neha"));


Ankit: 123.22
Neha: 3434.34
Rohit: 1378.0
Vijay: -19.08
Vinay: 99.22

Neha's new balance: 4434.34             

Download Source Code

Share on Google+Share on Google+

The Hashtable Class

Posted on: August 3, 2011 If you enjoyed this post then why not add us on Google+? Add us to your Circles



Discuss: The Hashtable Class  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image