Hashtable class

In this article, we will discuss Hashtable class – one of the Map implemented classes in detail

Key points about Hashtable:

Hashtable is legacy class and based on hashcode of keys where keys are unique and it is exactly same as HashMap with few differences with respect to following points

  • Synchronized methods
  • Performance
  • Null key insertion
  • Null value insertion

Hashtable:

  • Java Hashtable is the implementation class of Map interface (i.e.; Hashtable implements Map)
  • Java Hashtable uses hash table data structure to store Key-Value pairs, which is also known as Map entry
  • Java Hashtable is legacy class introduced in Java 1.0 version
  • Java Hashtable allows only unique keys but there is no restriction on values which can be duplicated
  • At any time, Java Hashtable contains only unique keys
  • Insertion-order is NOT maintained
  • While iterating through Java Hashtable, we will get map entries in random-order, as against insertion-order
  • Doesn’t allows NULL insertion for keys and values
  • Without generics, Java Hashtable allows to insert any type of Key/Values;
  • With generics, it is type-bounded except, if we take both Key-Value as Objects within angle brackets
  • Java Hashtable is synchronized, all methods of Java Hashtable is thread-safe (i.e.; only one thread is allowed to access, at a any given point of time)
  • Search operation is faster i.e.; searching any element from Java Hashtable is faster, as it uses hashing to store key-value pairs
  • Present in java.util package and extends java.util.Dictionary abstract class implements java.util.Map interface
  • Also, implements java.lang.Cloneable, java.io.Serializable marker interfaces which provides special ability to Hashtable (provided by JVM at run time)
  • java.lang.Cloneable: to create a duplicate object or to clone an object
  • java.io.Serializable: to transfer objects across network

037-hashtable-in-java Source: Team BenchResources.Net

Hashtable constructors:

Hashtable ht = new Hashtable();

  • creates an empty Hashtable object of size 11
  • with default fill ratio of 0.75

Hashtable ht = new Hashtable(int initialCapacity);

  • creates an empty Hashtable object of specified size (or initial capacity)
  • with default fill ratio of 0.75

Hashtable ht = new Hashtable(int initialCapacity, float loadFactor);

  • creates an empty Hashtable object of specified size (or initial capacity)
  • and specified fill ratio (for example 0.85)

Hashtable ht = new Hashtable(Map m);

  • creates an equivalent Hashtable object for the specified map
  • it is basically used for inter-conversion between map objects

Fill ratio (or Load factor)

  • Fill ratio is also known as Load factor
  • This factor determines when to increase the size of Java Hashtable automatically
  • For example, for the 1st two constructors the default load factor is 0.75 –> which means after filling 75% of original Java Hashtable, new Hashtable of bigger size will be created
  • For 3rd constructor, programmer can define load factor while creating Hashtable object. If programmer defines it to be 0.95, then after filling 95% of Hashtable, size of Hashtable will be increased automatically
  • The value of Load factor should be in between 0 to 1.0

Hashtable examples:

HashtableAddAndRemove.java

package in.bench.resources.java.collection;

import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class HashtableAddAndRemove {

	public static void main(String[] args) {

		// creating Hashtable object of type <Integer, String>
		Hashtable<Integer, String> hm = new Hashtable<Integer, String>();

		// adding key-value pairs to Hashtable object
		hm.put(1, "Google");
		hm.put(2, "Facebook");
		hm.put(3, "Yahoo");
		hm.put(4, "Amazon");
		hm.put(5, "Reddit");

		System.out.println("Printing all key-value pairs inside {}\n"
				+ hm + "\n");

		System.out.println("\nIterating using keySet\n");

		// Iterating key-pairs using keySet
		Set<Integer> keys = hm.keySet();
		for(Integer key : keys) {
			System.out.println(key + "  " + hm.get(key));
		}

		System.out.println("\n\nIterating using Map Entry interface\n");

		// Iterating key-pairs using Map entry
		Set set = hm.entrySet();
		Iterator iterator = set.iterator();

		while(iterator.hasNext()) {

			Map.Entry mapEntry = (Map.Entry)iterator.next();
			System.out.println(mapEntry.getKey() + "  "
					+ mapEntry.getValue());
		}

		// removing map entry at 4th position
		System.out.println("\n\nEntry removed at 4th position : "
				+ hm.remove(4));
	}
}

Output:

Printing all key-value pairs inside {}
{5=Reddit, 4=Amazon, 1=Google, 3=Yahoo, 2=Facebook}


Iterating using keySet

5  Reddit
4  Amazon
1  Google
3  Yahoo
2  Facebook


Iterating using Map Entry interface

5  Reddit
4  Amazon
1  Google
3  Yahoo
2  Facebook


Entry removed at 4th position : Amazon

Difference between HashMap and Hashtable ?

  • The main difference between HashMap and Hashtable is that, all methods of Hashtable class is synchronized whereas HashMap methods are non-synchronized
  • Hashtable is thread-safe, while working in multi-threaded environment
  • To make HashMap methods synchronized, we need to execute below code
    Map map = Collections.synchronizedMap(hashMap);
    

 

References:

 

Happy Coding !!
Happy Learning !!

HashMap v/s Hashtable
HashMap v/s HashSet