Java Hash table class

  • Hash table is an implementation of a key-value pair data structure in java. You can store and retrieve a value using a key and it is an identifier of the value stored. It is obvious that the key should be unique.
  • It contains only unique elements.
  • It is synchronized

java.util.Hashtable extends Dictionary and implements Map.

Example of Hashtable:

	import java.util.*; 

	class DemoHT{ 

	public static void main(String args[]){ 

	

	Hashtable ht=new Hashtable(); 

	

	ht.put(104,"A"); 

	ht.put(105,"B"); 

	ht.put(106,"R"); 

	ht.put(103,"O"); 

	

	for(Map.Entry m:ht.entrySet()){ 

	System.out.println(m.getKey()+" "+m.getValue()); 

	} 

	} 

	} 

	

				
				
				
				
						
						

Output


106 R

105 B

104 A

103 O



	

Difference between HashMap and Hashtable

But there are many differences between HashMap and Hashtable classes that are given below.

SN Hashtable Hashmap
1 Hashtable is synchronized. It is thread-safe and can be shared with many threads HashMap is non synchronized. It is not-thread safe and can't be shared between many threads without proper synchronization code..
2 Hashtable doesn't allow any null key or value HashMap allows one null key and multiple null values.
1 Hashtable is a legacy class. HashMap is a new class introduced in JDK 1.2
4 Hashtable is slow HashMap is fast
5 We can make the HashMap as synchronized by calling this code Map m = Collections.synchronizedMap(hashMap); Hashtable is internally synchronized and can't be unsynchronized.
6 Hashtable is traversed by Enumerator and Iterator HashMap is traversed by Iterator.
7 Iterator in HashMap is fail-fast Enumerator in Hashtable is not fail-fast.
8 HashMap inherits AbstractMap class. Hashtable inherits Dictionary class.

Methods inside HashTable are defined synchronized as below:

1.public synchronized boolean contains(Object obj){ ... }

2.public synchronized boolean contains Key(Object obj){ ... }

3.public synchronized Object get(Object obj){ ... }

4.public synchronized Object put(Object obj, Object obj1){ ... }

5.public synchronized Object remove(Object obj){ ... }