Hashtable example in Java

By: Ivan Lim Emailed: 1698 times Printed: 2196 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

Hashtable was part of the original java.util and is a concrete implementation of a Dictionary. However, Java 2 reengineered Hashtable so that it also implements the Map interface. Thus, Hashtable is now integrated into the collections framework. It is similar to HashMap, but is synchronized.

Like HashMap, Hashtable stores key/value pairs in a hash table. When using a Hashtable, you specify an object that is used as a key, and the value that you want linked to that key. The key is then hashed, and the resulting hash code is used as the index at which the value is stored within the table.

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().

The Hashtable constructors are shown here:

Hashtable( )
Hashtable(int size)
Hashtable(int size, float fillRatio)
Hashtable(Map m)

The first version is the default constructor. The second version creates a hash table that has an initial size specified by size. The third version creates a hash table that has an initial size specified by size and a fill ratio specified by fillRatio. This ratio must be between 0.0 and 1.0, and it determines how full the hash table can be before it is resized upward. Specifically, when the number of elements is greater than the capacity of the hash table multiplied by its fill ratio, the hash table is expanded. If you do not specify a fill ratio, then 0.75 is used. Finally, the fourth version creates a hash table that is initialized with the elements in m. The capacity of the hash table is set to twice the number of elements in m. The default load factor of 0.75 is used. The fourth constructor was added by Java 2.


The following example uses a Hashtable to store the names of bank depositors and their current balances:

// Demonstrate a Hashtable
import java.util.*;
class HTDemo {
public static void main(String args[]) {
Hashtable balance = new Hashtable();
Enumeration names;
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 hash table.
names = balance.keys();
while(names.hasMoreElements()) {
str = (String) names.nextElement();
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"));
}
}

The output from this program is shown here:

Ralph Smith: -19.08
Tom Smith: 123.22
John Doe: 3434.34
Todd Hall: 99.22
Jane Baker: 1378.0
John Doe's new balance: 4434.34

One important point: like the map classes, Hashtable does not directly support iterators. Thus, the preceding program uses an enumeration to display the contents of balance. However, you can obtain set-views of the hash table, which permits the use of iterators. To do so, you simply use one of the collection-view methods defined by Map, such as entrySet( ) or keySet( ). For example, you can obtain a set-view of the keys and iterate through them. Here is a reworked version of the program that shows this technique:

// Use iterators with a Hashtable.
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"));
}
}


Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(16)


1. View Comment

Finally a tutorial that clearly explains why Hashtable is called "hash", better than JDK's Java doc. Great work. Will definitely check out the rest of the tutorials on the site.

Thanks!


View Tutorial          By: Lisa Ander at 2011-10-27 20:33:15
2. View Comment

Thanks for the tutorial. I didn't get a lot of training or material on hashtable use and this really helped me out.

Keep up the great work!


View Tutorial          By: jordan at 2012-05-16 13:03:45
3. View Comment

Thanks for the tutorial.

One question: Since Hashtable is a generic requiring two types, shouldn't you specify the types, i.e.
Hashtable <String,Double> balance = new Hashtable<String,Double>();


View Tutorial          By: Stephen at 2012-06-09 06:36:23
4. View Comment

Thanks for the explanication

View Tutorial          By: Koklen at 2012-06-20 03:40:05
5. View Comment

Thanks!! Its very helpful.

View Tutorial          By: Tawfiiq at 2012-07-06 05:29:50
6. View Comment

Thanks for the tutorial. I want to create a catalog with more than two columns i.e. machinename, bestcost, maximumcost and deadline. Since hashtable allows only two columns. How can I extend it to come up with the four columns

View Tutorial          By: Lue at 2012-07-09 07:00:08
7. View Comment

Thank you for the tutorial. I want to create a catalog with four fields mac?hinetype, bestcost, maximumcost and deadline. Since hashtable allows only two fields how can I extend it to come up with the four fields

View Tutorial          By: Lue at 2012-07-09 10:40:08
8. View Comment

Thank you... :)
Simple and effective explanation.


View Tutorial          By: Mohammed Muzammil at 2012-08-08 05:07:32
9. View Comment

Hello sir, I observe that in the first version of your program you use have inserted "John Doe" first, but it prints "Ralph Smith" first. May i know the reason for this asynchronous behavior?

View Tutorial          By: Ganny at 2012-08-13 17:04:58
10. View Comment

This is probably a good java tutorial but it made me both angry and sad. Give me back my C# and Python :-(

View Tutorial          By: lol at 2012-09-15 21:20:09
11. View Comment

Why can't you just use an array for something like this? What is the advantage?

View Tutorial          By: Andrea at 2012-10-18 00:17:48
12. View Comment

Thank you a lot for sharing your knowledge! It was very helpful for me.

View Tutorial          By: Marcelo at 2013-01-17 03:07:37
13. View Comment

I want to store the Data in Vector or the LinkedList , and then that in HashTable ,

Means i select query result in Hash Table and Then print run time using JTable as Reort

HOW ???


View Tutorial          By: Sobia at 2013-01-17 11:24:59
14. View Comment

Excellent explanation. How can I take input from the commandline and add them to Hashtable in random?

View Tutorial          By: Joe at 2013-03-31 11:02:28
15. View Comment

a very rare but useful tutorial. Thanks a bunch!

but how can i use the map or HashMap??

looking forward to this tutorial


View Tutorial          By: Dalitso at 2014-02-19 12:07:34
16. View Comment

You do not give an example on fillratio i want to understand it

View Tutorial          By: reguieg at 2015-08-23 20:53:50

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Ivan Lim
Requesting a Signed Certificate from a Certification Authority example using keytool in Java
The if-then Statement in Java
SELECT Statements
The BodyTag Interface in JSP
Handling Duplicate Form Submissions in Struts
Standard Input and Output in C
A sample that shows Java Beans, Servlets and JSP working together
Recursion in C
Using Multibox in Struts
switch in C
Word Counting sample program in C
Java Bean Scopes in JSF
Using cout.width() in C++
Types of configurations in J2ME
How to get the CLDC and MIDP version from a J2ME program

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
How to Send SMS using Java Program (full code sample included)
InetAddress Example program in Java
XML and Java - Parsing XML using Java Tutorial
Inheritance Example in Java
Type Casting in Java
Simple Port Scanner application using Java
right shift operator, >>, in Java
Garbage collection and Finalize() method
Read from a COM port using Java program
Abstract classes in Java
Integer: byte, short, int, and long data types in Java
Student marks calculation program in Java
Calculate gross salary in Java
Stack example in Java - push(), pop(), empty(), search()
clone() and the Cloneable Interface in Java
Most Emailed Articles (in Java)
Write to a COM port using Java program
How to use ArrayList in Java
Java program for changeable wrapper class
History of Java
Data Types in Java
Sample program to demonstrate the use of ActionListener
Introducing JavaScript.
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Student marks calculation program in Java
Vector in Java - Sample Program
Save/Write/Read image file from/to a database using Java program
How to access instance from an inner class and accessing outer class variables in java
Method Override sample in Java
Using jar utility in Java - A jar tutorial