What is the difference between HashMap and Hashtable in Java?
Published May 16, 2022In Java, HashMap and Hashtable are very similar, and it can be difficult to differentiate between the two, especially if you are new to Java. For instance, both the Hashmap and hashtable are used to implement the Map interface in Java. In this tutorial, we are going to look at the core differences between HashMap and Hashtable.
The Difference between Hashmap and hashtable
The following are various differences between HashMaps and HasHtable
-
Synchronisation: While Hashtable is a synchronised collection, HashMap is not. Hashtable uses synchronised methods to prevent multi-threading issues.
-
Performance: Performance is another important difference between Hashtables and HashMaps. Due to the fact that HashMap and Hashtable are not synchronized, HashMap performs better.
-
Supporting Null Key: Due to its synchronized nature, Hashtables does not allow null keys, but HashMaps can allow null keys.
-
Fail Fast: In Hashtables, enumerations are used to iterate over keys and values, but iterators are used for HashMaps, which are fail-fast.
Example
import java.util.HashMap; import java.util.Hashtable; import java.util.Map; public class HashMaps_and_HasHtable { public static void main(String[] args) { Hashtable<Integer,String> myHashT=new Hashtable<Integer,String>(); myHashT.put(1," London"); myHashT.put(2,"Manchester"); System.out.println("This is a HashTable"); for (Map.Entry a:myHashT.entrySet()) { System.out.println(a.getKey()+" "+a.getValue()); } HashMap<Integer,String> myhashM=new HashMap<Integer,String>(); myhashM.put(3,"Mumbai"); myhashM.put(4,"Dubai"); System.out.println("This is a HashMap"); for (Map.Entry m:myhashM.entrySet()) { System.out.println(m.getKey()+" "+m.getValue()); }
} } |
Output
This is a HashTable
2 Manchester
1 London
This is a HashMap
3 Mumbai
4 Dubai
Keywords: Difference between HashMap and Hashtable, Java Collections, Java
Article Contributed By :
|
|
|
|
303 Views |