Hashtable in Java

Hashtable is  legacy class in Java.Vector is the thread safe version of  ArrayList.Similarly Hashtable is the thread safe version of HashMap.(But this thread  safety makes a performance downfall).The way by which data is inserted , iterated and deleted are shown the example code shown below.

import java.util.*;
public class HashtableSample {
HashtablehashTable = null;
public HashtableSample(){
public void addItems() {
System.out.println("Adding contents to Hashtable ");
hashTable = new Hashtable();
String[] listItems = {"dog", "cat", "cow", "elephant", "sheep"};
for (int i = 0; i < listItems.length; i++) { hashTable.put(i, listItems[i]); } } public void display() { System.out.println("Displaying contents of hashtable"); Set set = hashTable.entrySet(); System.out.println("Size = "+set.size()); Iterator i = set.iterator(); while (i.hasNext()) { Map.Entry entry = (Map.Entry) i.next(); System.out.print(entry.getKey() + ": "); System.out.println(entry.getValue()); } } public void removeItems() { int count = 0; while (count < 5) { hashTable.remove(count); count++; } System.out.println("Displaying contents after removal:"); display(); } public static void main(String[] args) { HashtableSample sample = new HashtableSample(); sample.addItems(); sample.display(); sample.removeItems(); } }

Now , let us see the output


Adding contents to Hashtable

Displaying contents of hashtable

Size = 5

4: sheep

3: elephant

2: cow

1: cat

0: dog

Displaying contents after removal:

Displaying contents of hashtable

Size = 0

Difference between HashMap and Hashtable

1)Hashtable is the thread safe version of HashMap . Somethods are synchronized .Hence  performance downfall is there in case of Hashtable.

2)HashMap permits null values as well as one null key.But Hashtable never allows these.


Hashtable implementation depends on the hash code values of  objects  using as keys .  If we use objects of a class as keys in a Hashtable then   our class needs to override hashCode() and equals() method.Otherwise meaningfully same objects  may be stored multiple times. This concept is well explained here.