Difference Between HashMap and HashTable - Scaler Topics (2024)

HashMap and HashTable are both key-value storage classes in Java. HashMap is non-synchronized, making it faster for single-threaded tasks, while HashTable is inherently synchronized, providing thread safety. HashTable doesn’t allow any null keys or values, but HashMap lets you have one null key and several null values. Additionally, HashMap can be molded to retain insertion order or sorted order using its various implementations, whereas HashTable doesn’t guarantee any particular order for its entries.

HashMap

A hashmap is a class that is a part of the Java collection framework since Java 1.2. This class belongs to java.util package. Java's Map interface can be implemented using this hashmap class. It usually stores the data in key, value pair (key, value), and you can access the value with the help of key in constant time, for example, an Integer. Inside a hashmap, one object is used as a key (index) to another object (value). If there is a key already existing in the hashmap and we again try to insert the same key, this time with a different value, then the value will be replaced with the new one of the corresponding key.

Syntax :

Example :

Output :

HashTable

A hashtable is a class that is a part of the Java collection framework. It implements a hash table, and it stores the data in key value pair (key, value). Inside a hashtable, we can store any non null object like a key or a value, that is, null values and keys are not allowed in hashtable. To store and retrieve objects successfully from a hashtable, the objects used as a key must implement the hashCode method and the equals method, that is the object which is used as a key is hashed, and the resulting hashCode which we get after hashing the object key is used as an index to get the value which is associated with the object key.

Although HashMap and HashTable are similar, there are certainly notable differences between them, let us discuss them.

Syntax :

Example :

Output :

Key Difference Between HashMap and HashTable

The main difference between HashMap and HashTable is their approach to synchronization and thread safety. While HashTable is inherently synchronized, ensuring that only one thread can access it at a time, HashMap is non-synchronized, allowing simultaneous access by multiple threads. This makes HashMap generally faster in single-threaded scenarios, due to the absence of synchronization overhead.

HashMap vs HashTable

ParameterHashMapHashTable
SynchronizationNon-synchronized. Multiple threads can access simultaneously, but synchronization must be externally handled for safe concurrent modification.Synchronized. Only one thread can access at a time, ensuring thread safety.
Null Values and KeysAllows one null key and multiple null values.Does not permit null keys or values. Inserting null can lead to a NullPointerException.
OrderingCan be used to implement LinkedHashMap (maintains insertion order) and TreeMap (sorted order).Does not guarantee any specific order for its entries.
Framework MembershipPart of the collection framework from its introduction. Implements the Map interface.Initially not part of the collection framework. Later integrated after implementing the Map interface.
Iterator BehaviorThe iterator is fail-fast. Throws ConcurrentModificationException if modified by another thread during iteration.Enumerator is not fail-fast. Due to internal synchronization, concurrent modification risks are minimized during enumeration.
Thread Waiting and PerformanceMultiple threads can operate without waiting. Generally offers better performance in single-threaded scenarios due to lack of synchronization overhead.Threads may need to wait due to synchronization. This can lead to performance overhead in multi-threaded scenarios.
Version IntroducedIntroduced in version 1.2.Introduced in version 1.0.
Legacy StatusNon-legacy.Considered legacy; newer implementations like HashMap are generally recommended.

Why HashTable Doesn’t Allow null and HashMap Do?

In the above differences between HashTable and HashMap, there is a point : A HashMap can allow null keys and values, whereas a HashTable does not allow null.

You must be wondering, why a HashMap can store a null whereas HashTable cannot store a null. Let us understand the reason in detail.

A HashTable stores the object in the key, value pair. In order to store and retrieve the object successfully, the object which is used as a key must implement the hashCode method and the equals method. Since null is not an object, it cannot implement these hashCode method and the equals method. So if we store null inside the HashTable, it will not work and throw a null pointer exception error. However, HashMap is a modern version of HashTable and it was created later. It will allow one null key and any number of null values.

Let us now understand the above points with an example.

Code in Java :

Output :

Explanation :

In the above code, we are implementing both the HashMap and HashTable inside the public class MyClass. To demonstrate our above point, we have added null inside both the HashMap and HashTable to check whether it is working. We can clearly see, that the HashMap is working completely fine after storing the null as its key, and value, and it is also printing its data. However, the HashTable throws an error null pointer exception after we added null as data inside it. Hence, we can conclude that the HashMap allows null, whereas the HashTable does not allow null.

Let us now don't add null inside the HashTable and check if it is working or not.

Code in Java :

Output :

Explanation :

We can clearly see, that if we are not adding null inside the HashTable, it is not throwing any error, and the code is working completely fine.

Conclusion

  • HashMap is a class within the Java collection framework introduced in Java 1.2. It implements the Map interface and stores data as key-value pairs.
  • HashTable implements a hash table and similarly stores data as key-value pairs.
  • For successful storage and retrieval in a HashTable, keys must implement both the hashCode and equals methods. The key’s hashCode, derived post-hashing, serves as an index to retrieve its associated value. Only non-null objects can be stored as keys or values.
  • We highlighted some distinctions between HashMap and HashTable.
  • HashMap is non-synchronized, while HashTable is synchronized.
  • HashMap can accommodate one null key and multiple null values. In contrast, HashTable prohibits both null keys and values, leading to a NullPointerException upon attempting such insertions.
  • Altering a HashMap during iteration can result in a ConcurrentModificationException. However, modifying a HashTable under the same conditions doesn’t raise any exceptions.
  • HashTable disallows null keys and values because, to function correctly, keys must implement the hashCode and equals methods. Since null isn’t an object, it doesn’t implement these methods, and attempting to store null in a HashTable results in a NullPointerException.
Difference Between HashMap and HashTable - Scaler Topics (2024)

FAQs

What is the main difference between HashMap and Hashtable? ›

The main difference between HashMaps and Hash Tables is their underlying data structure. HashMaps are implemented using an array of linked lists, where each element in the array is a linked list of key-value pairs. Hash Tables, on the other hand, use an array of buckets, where each bucket is a key-value pair.

What is the difference between HashMap and Hashtable and HashSet? ›

Hashtable and HashMap both implement Map , HashSet implements Set , and they all use hash codes for keys/objects contained in the sets to improve performance. Hashtable is a legacy class that almost always should be avoided in favor of HashMap .

What is the difference between HashMap and Hashtable and TreeMap? ›

HashMap is implemented as a hash table, and there is no ordering on keys or values. TreeMap is implemented based on red-black tree structure, and it is ordered by the key. LinkedHashMap preserves the insertion order. Hashtable is synchronized in contrast to HashMap .

Which of the following is true regarding the differences between Hashtable and ConcurrentHashMap in Java? ›

Hashtable locks the entire table during a write operation, thereby preventing other reads or writes. This could be a bottleneck in a high-concurrency environment. ConcurrentHashMap, however, allows concurrent reads and limited concurrent writes, making it more scalable and often faster in practice.

Why Hashtable is faster than HashMap? ›

Synchronization. Firstly, Hashtable is thread-safe and can be shared between multiple threads in the application. On the other hand, HashMap is not synchronized and can't be accessed by multiple threads without additional synchronization code. We can use Collections.

Can a HashMap have duplicate keys? ›

HashMap stores key, value pairs and it does not allow duplicate keys. If the key is duplicate then the old key is replaced with the new value. Dummy value: In HashMap no concept of dummy value, HashSet internally uses HashMap to add elements.

Does Hashtable allow duplicate keys? ›

A Hashtable does not accept duplicate keys. If you add a duplicate key the value will be replaced for that key. Here, you can see that when the key 1 is added again, the value is replaced with Kumaran. So, Hashtable does not accept duplicate keys.

What is the difference between Hashtable and synchronized HashMap? ›

Hashtable doesn't allow even a single null key and null values. Synchronized HashMap allows one null key and any number of null values. Iterators returned by Hashtable are fail-safe in nature. i.e they don't throw ConcurrentModificationException if the map is modified after the creation of the iterator.

What is the difference between HashMap and hash code? ›

Hashtable and HashMap are both used for implementing the Map interface. They use hashing techniques to store unique keys. However, the main difference between the two is that Hashtable is synchronized whereas HashMap is not. In this article on HashMap vs Hashtable, we will discuss HashMap and Hashtable individually.

Which Map is faster in Java? ›

HashMap will generally be fastest, since it has the best cache behavior ( HashMap iterates directly over the backing array, whereas TreeMap and LinkedHashMap iterate over linked data structures).

What is the difference between Hashtable and HashMap Mcq? ›

What is the difference between HashMap and Hashtable and HashSet? HashMap and Hashtable store key-value pairs, with HashMap allows nulls and are non-synchronized, while Hashtable is synchronized and doesn't allow nulls. HashSet only stores unique elements without key-value pairs, internally using a HashMap.

Can we store null values in a HashMap? ›

Yes, HashMap allows null key and null values. 1.2) Can a hashmap have multiple null keys and values? HashMap allows to store one null key and many null values i.e. many keys can have null value in java.

What is the basic difference between HashMap and HashTable? ›

HashMap and HashTable are both key-value storage classes in Java. HashMap is non-synchronized, making it faster for single-threaded tasks, while HashTable is inherently synchronized, providing thread safety. HashTable doesn't allow any null keys or values, but HashMap lets you have one null key and several null values.

What is the difference between HashMap and HashSet and HashTable? ›

A HashSet is an implementation of a set - a collection of unique keys. HashMap and HashTable are both implementations of a Map - a collection of key value pairs where the keys are unique (kind of like a lookup table). HashTable is thread safe, but HashMap is not. HashTable does not allow a null key, but HashMap does.

What is the difference between HashMap and concurrent HashMap? ›

HashMap isn't thread-safe at all. Thus, it is non-synchronized in nature. The ConcurrentHashMap, on the other hand, is thread-safe. Due to non-synchronization, the performance of HashMap is relatively higher, and various threads are capable of performing simultaneously.

What is the difference between a map and a dictionary and a Hashtable? ›

Dicts store an arbitrary number of objects, each identified by a unique dictionary key. Dictionaries are often also called maps, hashmaps, lookup tables, or associative arrays. They allow the efficient lookup, insertion, and deletion of any object associated with a given key.

How is a Hashtable different from an ordered map? ›

The hash table has been synchronised. STL Maps are not thread safe, whereas Hashmaps are thread safe and can be shared by multiple threads. Value Order: Values in an STL map are stored in sorted order, whereas values in a hash table are not stored in sorted order.

Top Articles
Cryptographie à clé publique : Tout savoir
Hadoop Data Node Activity Test
English Bulldog Puppies For Sale Under 1000 In Florida
Katie Pavlich Bikini Photos
Gamevault Agent
Pieology Nutrition Calculator Mobile
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Compare the Samsung Galaxy S24 - 256GB - Cobalt Violet vs Apple iPhone 16 Pro - 128GB - Desert Titanium | AT&T
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Craigslist Dog Kennels For Sale
Things To Do In Atlanta Tomorrow Night
Non Sequitur
Crossword Nexus Solver
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Energy Healing Conference Utah
Geometry Review Quiz 5 Answer Key
Hobby Stores Near Me Now
Icivics The Electoral Process Answer Key
Allybearloves
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Pearson Correlation Coefficient
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Marquette Gas Prices
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Vera Bradley Factory Outlet Sunbury Products
Pixel Combat Unblocked
Movies - EPIC Theatres
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Mia Malkova Bio, Net Worth, Age & More - Magzica
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Topos De Bolos Engraçados
Sand Castle Parents Guide
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Hello – Cornerstone Chapel
Stoughton Commuter Rail Schedule
Nfsd Web Portal
Selly Medaline
Latest Posts
Article information

Author: Maia Crooks Jr

Last Updated:

Views: 5955

Rating: 4.2 / 5 (43 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Maia Crooks Jr

Birthday: 1997-09-21

Address: 93119 Joseph Street, Peggyfurt, NC 11582

Phone: +2983088926881

Job: Principal Design Liaison

Hobby: Web surfing, Skiing, role-playing games, Sketching, Polo, Sewing, Genealogy

Introduction: My name is Maia Crooks Jr, I am a homely, joyous, shiny, successful, hilarious, thoughtful, joyous person who loves writing and wants to share my knowledge and understanding with you.