Difference between HashMap and HashTable

Hashtable is basically a datastructure to retain values of key-value pair.
  • It didn’t allow null for both key and value. You will get NullPointerException if you add null value.
  • It is synchronized. So it comes with its cost. Only one thread can access in one time

Hashtable<Integer,String>; cityTable = new Hashtable<Integer,String>();
cityTable.put(1, "Lahore");
cityTable.put(2, "Karachi");
cityTable.put(3, null); /* NullPointerEcxeption at runtime*/

Like Hashtable it also accepts key value pair.
  • It allows null for both key and value
  • It is unsynchronized. So come up with better performance
HashMap<Integer,String> productMap = new HashMap<Integer,String>();
productMap.put(1, "Keys");
productMap.put(2, null);

HashSet does not allow duplicate values. It provides add method rather put method. You also use its contain method to check whether the object is already available in HashSet. HashSet can be used where you want to maintain a unique list.
HashSet<String> stateSet = new HashSet<String>();
stateSet.add ("CA");
stateSet.add ("WI");
stateSet.add ("NY");
if (stateSet.contains("PB")) /* if CA, it will not add but shows following message*/
     System.out.println("Already found");

The key differences between the two are
1.Hashmap is not synchronized in nature but hashtable is.
2. Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't.
Fail-safe - if the Hashtable is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationExceptionâ€?
3. HashMap permits null values and only one null key, while Hashtable doesn't allow key or value as null.

Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email