Image of Hashtable VS HashMap

ADVERTISEMENT

Table of Contents

Introduction

Hashing objects like HashMap and Hashtable are mostly used for storing and caching data as a key/value pairs inside the memory.

In this tutorial, we list the major similarities and differences between these 2 data types.

1- Similarities

  • Both expose the same interface for adding, removing and accessing elements from the memory.
  • get(): retrieve an item by a key.
  • remove(): remove an item by a key.
  • put(): add an item

so both types can interchangeably be used for caching or storing key/value pairs inside the memory.

  • Both belong to the same package java.util.

2- Differences

There are a lot of differences between HashMap and Hashtable, here below we list the major ones:

  • Hashtable is implicitly synchronized, it works perfectly with multi-threaded environments. Upon each access, the thread acquires a lock on the Hashtable hence preventing any other thread from modifying it simultaneously. In contrast, HashMap is not thread safe and is only suitable for single-threaded environments. If you want to use HashMap in a multi threaded environment you can use ConcurrentHashMap.
  • HashMap is faster than Hashtable due to the fact that Hashtable implicitly checks for synchronization on each method call even in a single thread environment.
  • HashMap allows storing null values, while Hashtable doesn’t.
  • HashMap can be iterated by an Iterator which is considered as fail-fast . i.e. if any other thread modifies the map while iterating over it then a ConcurrentModificationException exception is thrown. However, Hashtable is iterated by an Enumerator which is not fail-fast.
  • HashMap allows ordering and sorting its items through LinkedHashMap and TreeMap implementations, while this is not feasible with Hashtable.

In short, Hashtable is deprecated and replaced officially by ConcurrentHashMap, there is no reason for using it in new projects unless you’re working in a legacy code which doesn’t support HashMap (ideally there shouldn’t be an applications which just compile on versions < 1.2 as HashMap is introduced in JDK 1.2).

Summary

Hashing objects like HashMap and Hashtable are mostly used for storing and caching data as a key/value pairs inside the memory.

Next Steps

If you're interested in learning more about the basics of Java, coding, and software development, check out our Coding Essentials Guidebook for Developers, where we cover the essential languages, concepts, and tools that you'll need to become a professional developer.

Thanks and happy coding! We hope you enjoyed this article. If you have any questions or comments, feel free to reach out to jacob@initialcommit.io.

Final Notes