Java Hashtable complete guide with examples

0
2440

In this article we will learn what is Java Hashtable, when and how do we use it in Java applications and how Hashtable works internally in java with simple examples.

1. What is Hashtable in java

Java Hashtable is a legacy implementation class of the Map interface and an implementation of hash table data structure.  It inherits Dictionary class and implements the Map interface.

2. Features of Java Hashtable

  1. Hashtable class implements the java.util.Mapinterface, the under lying data structure is hash table.
  2. Insertion order is not preserved and it is based on hash code of the keys.
  3. Null key (or) null value is not allowed otherwise we will get NullPointerException.
  4. Duplicate keys are not allowed but values can be duplicated. To follow this, the objects used as keys must implement the hashCode method and the equals method.
  5. Java Hashtable methods are synchronized.

3. When do we use Hashtable?

The general purpose of map in java is to hold key value pairs, for example if we wants to hold a student roll number and and his name (roll number is a key as it is unique and name can be value). Either Hashtable or HashMap having hash table implementation is underlying data structure. The key difference between Hashtable and HashMap is synchronization. All the Hashtable methods are synchronized in java, hence Hashtable operations are thread safe. HashMap operations are relatively faster than Hashtable operations if we considered multiple threads.

4. How to create Hashtable?

Following are the constructors java Hashtable provides to create Hashtable insatnces.

Constructors :

  1. Hashtable():  Constructs a new, empty hashtable with a default initial capacity 11.
  2. Hashtable(int size) :  Constructs a new, empty hashtable with the specified initial capacity and default load factor (0.75).
  3. Hashtable(int size, float fillRatio) : Constructs a new, empty hashtable with the specified initial capacity and the specified load factor.
  4. Hashtable(Map m) :  Constructs a new hashtable with the same mappings as the given Map (useful to convert other map implementation to Hastable).

RollNo class to add Student RollNos in Hashtable.

public class RollNo {
 
  int rollNo;
 
  RollNo(int rollNo) {
    this.rollNo = rollNo;
  }
  public int hashCode() {
    return rollNo;
  }

  public String toString() {
    return rollNo + "";
  }
}

Add RollNos to Hashtable.

Hashtable<RollNo, String> h = new Hashtable<>();
h.put(new RollNo(6),"A");
h.put(new RollNo(5),"B");
h.put(new RollNo(2),"C");
h.put(new RollNo(23),"D");
h.put(new RollNo(15),"E");
h.put(new RollNo(16),"F");
System.out.println(h); //{6=A, 16=F, 5=B, 15=E, 2=C, 23=D}

5. Internal working of Hashtable in java

When you create a new hastable instance, a new empty hashtable will be created with initial capacity 11. Hashtable uses an array and each position in the arrays is a bucket which can. The formula calculates an index for the key is:

int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;

Following image illustrates how hashtable stores key value pairs based on hash code and how it get index. To understand little deeper, in this example we have created a RollNo class to use roll number as key and hashcode() method overridden in RollNo class, so that we know that exactly what is the hash code of a key, in this example the key itself is hashcode.

Java HashTable Data Structure

5.1. Collisions

If you notice at Index 5, two key value pairs stored in that bucket, even different hash codes generates the same index. A single bucket stores multiple entries, we refer to this as a collision. Which must be searched sequentially, to resolve collisions Hashtable stores key value pairs in a linked list in each bucket, this is called chaining.

5.2. rehash() in Hashtable

By default the load factor is 0.75 in Hashtable, array capacity doubles when 3/4 th of buckets not empty in Hashtable. This operation is executed by rehash() method in Hashtable class.

For Example, if the 8 (3/4 th of initial capacity ) buckets are filled in the array, the new capacity become 23.

int newCapacity = (oldCapacity << 1) + 1;

Following image illustrates that how rehashing works in java Hashtable.

Java Hashtable example

To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method., should follow the hashcode() contract.

6. Java Hashtable methods

All the Hashtable methods works same as the HashMap methods , the key difference is all the Hashtable methods are synchronized. For the detailed code examples of Hashtable refer to HashMap.

7. How to iterate Java Hashtable?

Following example shows you how to loop HashTable using Enumeration and forEach().

public class HashTable_Iterate_Demo {

	public static void main(String[] args) {
		  Hashtable<Integer, String> h = new Hashtable<>();
		  
			h.put(1,"A");
			h.put(2,"B");
			h.put(3,"C");
			h.put(4,"D");
			h.put(5,"E");
			h.put(6,"F");
			h.put(7,"G");
			h.put(8,"H");
			h.put(22,"I");
			h.put(0,"K");
			h.put(23,"J");
			h.put(25,"L");
			
			System.out.println(h); //{22=I, 8=H, 7=G, 6=F, 5=E, 4=D, 3=C, 2=B, 1=A, 23=J, 0=K}	
			
			// Iterate using Enumeration
			System.out.println("------------------");
			Enumeration<Integer> e = h.keys();
			while(e.hasMoreElements()) {
				Integer i = e.nextElement();
				System.out.println("Key : " + i + ", value : " + h.get(i));
			}
			
			System.out.println("------------------");
			// Iterate using forEch method
			h.forEach( (key, value) -> {
				System.out.println("Key : " + key + ", value : " + value);
			});
		}
}

Output :

{22=I, 8=H, 7=G, 6=F, 5=E, 4=D, 3=C, 25=L, 2=B, 1=A, 23=J, 0=K}
------------------
Key : 22, value : I
Key : 8, value : H
Key : 7, value : G
Key : 6, value : F
Key : 5, value : E
Key : 4, value : D
Key : 3, value : C
Key : 25, value : L
Key : 2, value : B
Key : 1, value : A
Key : 23, value : J
Key : 0, value : K
------------------
Key : 23, value : J
Key : 0, value : K
Key : 1, value : A
Key : 25, value : L
Key : 2, value : B
Key : 3, value : C
Key : 4, value : D
Key : 5, value : E
Key : 6, value : F
Key : 7, value : G
Key : 8, value : H
Key : 22, value : I

There are different approaches to iterate java Hashtable, all of them explained in detailed iterate java map article. They are common to iterate any map implementation class in java.

8. Conclusion

In this article we have covered what is java Hashtable class, its features, how internally Hashtable works, how rehashing works and the importance of hashcode() method and about collisions in java Hashtable.

References

  1. Java document
  2. Java ArrayList
  3. Java HashSet
  4. Java HashMap

LEAVE A REPLY

Please enter your comment!
Please enter your name here