Hashtable vs HashMap

Since, my previous blog gives you clear distinguish between Vector & ArrayList. Now let me describe the difference between Hashtable & HashMap. Every Java developer should aware about this, hence they will use appropriately in their developing applications. Both have similar data structure, storing as key/value pairs but subtle differences.


  • Hashtable is synchronized,  hence its called thread safe meaning multiple threads can access the object concurrently without affecting its data.
  • It does not allow null keys or values.
  • Enumeration is not fail-safe. It allows you to change the Hashtable content while traversing.


  • Hashmap is unsynchronized. You need to externally synchronize the hash map object for supporting concurrent programming.
  • It does allows null keys and values.
  • Iterator is fail-safe, because it won’t allow you to change the Map while doing iteration.
  • Allows to safely remove the map entries during iteration.

Following code snippet gives you clear picture about the differences.

Point 2: null keys & values

Hashtable table = new Hashtable();
table.put("blog1", "VectorVsArrayList");
table.put("blog2", "HashtableVsHashMap");
//table.put(null, null); //throws NullPointerException

HashMap map = new HashMap();
map.put("blog1", "VectorVsArrayList");
map.put("blog2", "HashtableVsHashMap");
map.put(null, null);// allows null values

Point 3: Fail-Safe during iteration of object.

Enumeration e = table.keys();
table.put("blog3", "Not Fail Safe"); //allows it. doesn't throw any exception
System.out.println("table values are : " +e.nextElement());

Set s = map.keySet();
Iterator itr = s.iterator();
//map.put("blog3","Fail-Safe"); //throws ConcurrentModificationException
System.out.println("map values are : " +itr.next());

You can also define the synchronized hash map, by implementing like this.

HashMap map = Collections.synchronizedMap(new HashMap());

Tags: , , , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: