Krivalar Tutorials 
Krivalar Tutorials


Difference Between HashMap and Hashtable

HashMapHashtable
HashMap allows to store one entry with null as keyHashtable doesnot allow null as key
HashMap allows to store many entries with null as value in the key-value pairHashtable doesnot allow null as value in key-value pair
HashMap is not Synchronized and hence not safe in MultithreadingHashtable is Synchronized safe in Multithreading but only one thread can access at a time
HashMap provides higher speed/performance compared to HashtableRelatively slow because Hashtable supports multithreading
LinkedHashMap and PrinterStateReasons are derived classes of HashMapProperties and UIDefaults are derived classes of Hashtable


Example - Java Program using HashMap and HashTable



import java.util.HashMap;
import java.util.Hashtable;

public class HashMapVsHashTable {
	public static void main (String args[]) {

		System.out.println("------ HashMap -----");
		HashMap colourMap
				= new HashMap();
		colourMap.put(1, "Red");
		colourMap.put(2, "Green");
		colourMap.put(3, "Blue");
		colourMap.put(4, "Yellow");
		//will store one entry with key null
		colourMap.put(null, null);
		System.out.println(colourMap);

		//will replace the entry with key null
		colourMap.put(null, "new");
		System.out.println(colourMap);

		colourMap.remove(3);
		System.out.println(colourMap);

		//For each element, form new string
		//by concatenating Flower and
		//replace all elements with the new String
		colourMap.replaceAll(
				(x,y) -> (y + " Ok") );
		System.out.println(colourMap);

		System.out.println("------ Hashtable -----");
		Hashtable fruitTable
					= new Hashtable();
		fruitTable.put(1, "Apple");
		fruitTable.put(2, "Orange");
		fruitTable.put(3, "Mango");
		fruitTable.put(4, "Grape");

		System.out.println(fruitTable);

		fruitTable.remove(2);
		System.out.println(fruitTable);

		//For each element,
		//take substring of first 4 characters
		//starting from index 0
		//and replace all elements with the new String
		fruitTable.replaceAll(
				(x,y) -> (y.substring(0,4)));
		System.out.println(fruitTable);
		//will throw a null pointer exception
		fruitTable.put(null, null);
	}
}


The above program would display the result shown below:

------ HashMap -----
{null=null, 1=Red, 2=Green, 3=Blue, 4=Yellow}
{null=new, 1=Red, 2=Green, 3=Blue, 4=Yellow}
{null=new, 1=Red, 2=Green, 4=Yellow}
{null=new Ok, 1=Red Ok, 2=Green Ok, 4=Yellow Ok}
------ Hashtable -----
{4=Grape, 3=Mango, 2=Orange, 1=Apple}
{4=Grape, 3=Mango, 1=Apple}
{4=Grap, 3=Mang, 1=Appl}
Exception in thread "main"
java.lang.NullPointerException
	at java.util.Hashtable.put
		(Hashtable.java:460)
	at HashMapVsHashTable.main
		(HashMapVsHashTable.java:53)


<< Vector vs ArrayList    abstract Keyword >>



























Searching using Binary Search Tree