# Programming Tutorials

## 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[]) {
Hashtable balance = 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.08Tom Smith: 123.22John Doe: 3434.34Todd Hall: 99.22Jane Baker: 1378.0John 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[]) {
Hashtable balance = 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.08Todd Hall: 99.22 John Doe: 3434.34 Jane Baker: 1378.0Tom Smith: 123.22
John Doe's new balance: 4434.34```
{"ft_lang_label":"__label__en","ft_lang_prob":0.79126006,"math_prob":0.84222,"size":7017,"snap":"2023-40-2023-50","text_gpt3_token_len":1635,"char_repetition_ratio":0.12519607,"word_repetition_ratio":0.120035306,"special_character_ratio":0.2570899,"punctuation_ratio":0.1676259,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9610504,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2023-10-04T01:02:00Z\",\"WARC-Record-ID\":\"<urn:uuid:fa32259a-fceb-46cf-8c69-7b798d9541e2>\",\"Content-Length\":\"52090\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:ffe07c45-0e4e-4ba5-81fa-7752c370d133>\",\"WARC-Concurrent-To\":\"<urn:uuid:ff27e546-3061-4739-9422-4eee8c64e224>\",\"WARC-IP-Address\":\"104.21.45.80\",\"WARC-Target-URI\":\"https://java-samples.com/showtutorial.php?tutorialid=375\",\"WARC-Payload-Digest\":\"sha1:C442CHENUEUMFRB754PLCAKR2KZXAULK\",\"WARC-Block-Digest\":\"sha1:N7M77M5XNLQGZPGZDAMXNWNXWSFK5ECY\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2023/CC-MAIN-2023-40/CC-MAIN-2023-40_segments_1695233511284.37_warc_CC-MAIN-20231003224357-20231004014357-00537.warc.gz\"}"}