There are few differences between HashMap and Hashtable. This example illustrates the key differences with simple example.
- 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. If you want to make HashTable thread-safe, use
Collections.synchronizedMap(map)
orConcurrentHashMap
class. - Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.
- 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.
- Iterator in the HashMap is fail-fast and throw
ConcurrentModificationException
if any other Thread modifies the map structurally by adding or removing any element except Iterator’s own remove() method.
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}