Hashtable example in Java
By: Ivan Lim in Java Tutorials on 2007-09-14
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:
import java.util.*; class HTDemo { public static void main(String args[]) { Hashtablebalance = new Hashtable<>(); Enumeration<String> names; String str; double bal; balance.put("John Doe", 3434.34); balance.put("Tom Smith", 123.22); balance.put("Jane Baker", 1378.00); balance.put("Todd Hall", 99.22); balance.put("Ralph Smith", -19.08); // Show all balances in hash table. names = balance.keys(); while(names.hasMoreElements()) { str = names.nextElement(); System.out.println(str + ": " + balance.get(str)); } System.out.println(); // Deposit 1,000 into John Doe's account bal = balance.get("John Doe"); balance.put("John Doe", 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:
import java.util.*; class HTDemo2 { public static void main(String args[]) { Hashtablebalance = new Hashtable<>(); String str; double bal; balance.put("John Doe", 3434.34); balance.put("Tom Smith", 123.22); balance.put("Jane Baker", 1378.00); balance.put("Todd Hall", 99.22); balance.put("Ralph Smith", -19.08); // show all balances in hashtable Set<String> set = balance.keySet(); // get set-view of keys // get iterator Iterator<String> itr = set.iterator(); while(itr.hasNext()) { str = itr.next(); System.out.println(str + ": " + balance.get(str)); } System.out.println(); // Deposit 1,000 into John Doe's account bal = balance.get("John Doe"); balance.put("John Doe", bal+1000); System.out.println("John Doe's new balance: " + balance.get("John Doe")); } }
The output is shown here:
Ralph Smith: -19.08
Todd Hall: 99.22
John Doe: 3434.34
Jane Baker: 1378.0
Tom Smith: 123.22 John Doe's new balance: 4434.34
Add Comment
This policy contains information about your privacy. By posting, you are declaring that you understand this policy:
- Your name, rating, website address, town, country, state and comment will be publicly displayed if entered.
- Aside from the data entered into these form fields, other stored data about your comment will include:
- Your IP address (not displayed)
- The time/date of your submission (displayed)
- Your email address will not be shared. It is collected for only two reasons:
- Administrative purposes, should a need to contact you arise.
- To inform you of new comments, should you subscribe to receive notifications.
- A cookie may be set on your computer. This is used to remember your inputs. It will expire by itself.
This policy is subject to change at any time and without notice.
These terms and conditions contain rules about posting comments. By submitting a comment, you are declaring that you agree with these rules:
- Although the administrator will attempt to moderate comments, it is impossible for every comment to have been moderated at any given time.
- You acknowledge that all comments express the views and opinions of the original author and not those of the administrator.
- You agree not to post any material which is knowingly false, obscene, hateful, threatening, harassing or invasive of a person's privacy.
- The administrator has the right to edit, move or remove any comment for any reason and without notice.
Failure to comply with these rules may result in being banned from submitting further comments.
These terms and conditions are subject to change at any time and without notice.
- Data Science
- Android
- React Native
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
Read a file having a list of telnet commands and execute them one by one using Java
Open a .docx file and show content in a TextArea using Java
Step by Step guide to setup freetts for Java
Of Object, equals (), == and hashCode ()
Using the AWS SDK for Java in Eclipse
DateFormat sample program in Java
concurrent.Flow instead of Observable class in Java
Calculator application in Java
Sending Email from Java application (using gmail)
Comments