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}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Pin It on Pinterest

Share This

Share this post with your friends!

Share This

Share this post with your friends!