Difference Between HashMap And Hashtable

There are few differences between HashMap and Hashtable. This example illustrates the key differences with simple example.

  1. Hashtable is synchronized where as HashMap is not synchronized. It is one of the key difference between HashMap and HashTable. HashMap offers better performance than HashTable in the multi-threaded environments.
  2. Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.
  3. One of HashMap’s subclasse is LinkedHashMap, so in the event that you’d want predictable iteration order , you caneasily use HashMap for a LinkedHashMap. This is not possible if you were using Hashtable.

Lets look at the example.

HashMapExample.java

package javabeat.net.core;

import java.util.HashMap;

/**
 * HashMap Example
 *
 * @author Krishna
 *
 */
public class HashMapExample {
	public static void main(String[] args) {
		HashMap<String,String> map = new HashMap<String,String>();
		map.put("1", "one");
		map.put("2", "two");
		map.put("3", "three");

		//Overwritten previous value
		map.put("2", "2");

		//Map accepts null key
		map.put(null, "four");

		//Map accepts null value
		map.put("5", null);

		System.out.println(map);
	}
}

Output…

{null=four, 3=three, 2=2, 1=one, 5=null}

HashTableExample.java

package javabeat.net.core;

import java.util.Hashtable;

/**
 * HashTable Example
 *
 * @author Krishna
 *
 */
public class HashTableExample {
	public static void main(String[] args) {
		Hashtable<String,String> map = new Hashtable<String,String>();
		map.put("1", "one");
		map.put("2", "two");
		map.put("3", "three");

		//Overwritten previous value
		map.put("2", "2");

		//Map not accepts null key
		//map.put(null, "four"); - NullPointerException

		//Map not accepts null value
		//map.put("5", null); - - NullPointerException

		System.out.println(map);
	}
}
{3=three, 2=2, 1=one}

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*