FROMDEV

Java HashMap and Hashtable : The Key Differences You Must Understand

HashMap and Hashtable are important data structures supported by Java collections framework.
Every java interview contains several java collections framework questions focused on Hashmap and similar classes in collections API.

This tutorial explains significant advantages and disadvantages of HashMap and Hashtable used by developers for java application development.

This post is written by java professional to explain the worth of HashMap and Hashtable in making of java apps and learning from useful java books. Let’s get started.

Advantages of HashMap

  • When you add items to a HashMap, you are not guaranteed to retrieve the items in the same order you put them in. There are subclasses of HashMap like LinkedHashMap that will maintain the order, but in general order is not guaranteed with a Map. 
  • The purpose of a map is to store items based on a key that can be used to retrieve the item at a later point. 
  • Collection functionality some great utility functions are available for lists via the Collections class. 
  • HashMap is non synchronized.HashMap cannot be shared between multiple threads without proper synchronization.Synchronized means only one thread can modify a hash table at one point of time. 
  • HashMap is a fail-fast iterator. 

Disadvantages of HashMap

  • You can’t lock the whole map to find the size of the map. Iterators are weakly consistent. 
  • HashMap does not guarantee that the order of the map will remain constant over time. 

Advantages of HashTable

  • HashTable may have not have any null key or value. 
  • Hashtable is an implementation of a key-value pair data structure in java. You can store and retrieve a ‘value’ using a ‘key’ and it is an identifier stored. It is obvious that the ‘key’ should be unique. 

Disadvantages of HashTable

  • Hashtable is synchronized, which means Hashtable is thread-safe and can be shared between multiple threads 
  • Synchronization Hashtable is much slower than HashMap 

Uses of HashMap

The HashMap class uses a hashtable data structure to implement the Map interface. This allows the execution time of basic operations, such as get( ) and put( ), to remain constant even for large sets.

  • HashMap is a popular class in almost all useful java libraries.
  • HashMap can be easily used at places where fast retrieval of data is required using a key.

Uses of HashTable

Hashtable stores key/value pairs in a hash table. When using a Hashtable, you specify an object that is used as a key, and the value that you want linked to that key. The key is then hashed, and the resulting hash code is used as the index at which the value is stored within the table.

  • Hashtable is a legacy class and has been used in several java libraries prior to introduction of HashMap.
  • Its not officially deprecated, however no experienced java programmer should be using this in latest java versions. For all practical purposes HashMap can be used in different ways to achieve same or better results.

Closer Looks At The HashMap Class

The HashMap class extends AbstractMap and implements the Map interface. It uses a hash table to store the map. This allows the execution time of get( ) and put( ) to remain constant even for large sets. HashMap maintains key and value pairs.HashMap is a generic class that has this declaration

class HashMap<K, V&gt

Here, K specifies the type of keys, and V specifies the type of values.

The following constructors are defined:

HashMap( )
HashMap(Map m)
HashMap(int capacity)
HashMap(int capacity, float fillRatio)

  • Both key and value is stored in the bucket as a form of Entry object.
  • The first form constructs a default hash map.
  • The second form initializes the hash map by using the elements of m.
  • The third form initializes the capacity of the hash map to capacity.
  • The fourth form initializes both the capacity and fill ratio of the hash map by using its arguments.
  • HashMap implements Map and extends AbstractMap. It does not add any methods of its own.
  • It is used for maintaining key and value mapping.
  • HashMap is similar to Hashtable with two exceptions – HashMap methods are unsynchronized and it allows null key and null values unlike Hashtable.
  • You should note that a hash map does not guarantee the order of its elements. Therefore, the order in which elements are added to a hash map is not necessarily the order in which they are read by an iterator.
  • It maintains no order.
  • It may have one null key and multiple null values.
  • It contains only unique elements.
  • There can only be one null key in HashMap
  • HashMap implementation LinkedHashMap maintains the insertion order and TreeMap sorts the mappings based on the ascending order of keys.
  • HashMap implements Map interface and is a part of collection framework since the beginning.

The following program illustrates HashMap.

import java.util.HashMap;

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

// create new HashMap.
// … Uses diamond inference on right side.
HashMap hash = new HashMap&lt;&gt;();
// Put three keys with values.
hash.put(1, “Car”);
hash.put(2, “Bike”);
hash.put(3, “Truck”);
// Look up some known values.
int a = hash.get(1);
int b = hash.get(2);
// Display results.
System.out.println(a);
System.out.println(b);
}
}

Output

Car
Bike

Put, get. The put method receives two arguments. The first argument is the key we are trying to add to the HashMap. And the second is the value linked to that key.

A Closer Look At HashTable Class

  • Hashtable was part of the original java.util and is a concrete implementation of a Dictionary.
  • However, with the advent of collections, Hashtable was reengineered to also implement the Map interface. Thus, Hashtable is now integrated into the Collections Framework. It is similar to HashMap, but is synchronized.
  • HashMap, Hashtable stores key/value pairs in a hash table. However, neither keys nor values can be null.
  • The key is then hashed, and the resulting hash code is used as the index at which the value is stored within the table.

It is declared like this:

class HashMap<K, V&gt

Here, K specifies the type of keys, and V specifies the type of values.

  • A hash table can only store objects that override the hashCode( ) and equals( ) methods that are defined by Object. The hashCode( ) method must compute and return the hash code for the object.
  • For example, the most common type of Hashtable uses a String object as the key. String implements both hashCode( ) and equals( ).
  • The Hashtable constructors are shown here:

Hashtable( )
Hashtable(int size)
Hashtable(int size, float fillRatio)
Hashtable(Map m)

  • The first version is the default constructor.
  • The second version creates a hash table that has an initial size specified by size. (The default size is 11.)
  • The third version creates a hash table that has an initial size specified by size and a fill ratio specified by fillRatio. This ratio must be between 0.0 and 1.0, and it determines how full the hash table can be before it is resized upward. Specifically, when the number of elements is greater than the capacity of the hash table multiplied by its fill ratio, the hash table is expanded. If you do not specify a fill ratio, then 0.75 is used.
  • The fourth version creates a hash table that is initialized with the elements in m. The capacity of the hash table is set to twice the number of elements in m. The default load factor of 0.75 is used.
  • Hashtable doesn’t guarantee any kind of order. It doesn’t maintain the mappings in any particular order.
  • Initially Hashtable was not the part of Collection Framework it has been made a collection framework member later after being retrofitted to implement the Map interface.
  • The following program illustrate HashTable.

import java.util.Hashtable;

import java.util.Enumeration;

public class HashtableExample {

public static void main(String [] args) {

Enumeration names;
String key;

// Creating a Hashtable

Hashtable hashtable = new Hashtable();

// adding Key and Value pairs to Hashtable

hashtable.put(“Key1”, “A”);

hashtable.put(“Key2”, “B”);

hashtable.put(“Key3”, “C”);

hashtable.put(“Key4”, “D”);

hashtable.put(“Key5”, “E”);

names = hashtable.keys();

while(names.hasMoreElements()) {

key = (String) names.nextElement();

System.out.println(“Key: “+key+” &amp; Value: ” +

hashtable.get(key));

}
}
}

Output

Key: Key4 & Value: D
Key: Key3 & Value: C
Key: Key2 & Value: B
Key: Key1 & Value: A
Key: Key5 & Value: E

Conclusion

This blog is published by java professional to explain all major advantages and disadvantages of HashMap and HashTable. Hope you have realized the importance of using both HashMap and Hashtable in java application development and make best development practices.

James Warner is a highly qualified digital marketing and entrepreneurship. I’m a contributing editor of NexSoftsys for many years in a various role including editor Technology, Health & Media editor and also working as a freelance. You can contact me on Facebook or Follow me on Twitter

Article Updates

  • Article Updated on September 2021. Some HTTP links are updated to HTTPS. Updated broken links with latest URLs. Some minor text updates done. Content validated and updated for relevance in 2021.
Exit mobile version