by BehindJava

What are Hash Tables in Data Structures

Home » datastructures » What are Hash Tables in Data Structures

In this blog, we are going to learn about HashTables in detail.

Hash Tables

  • It is an abstract data type.
  • Provide access to data using keys.
  • Key doesn’t have to be an integer.
  • Consists of Key and value pairs and data types can be different.
  • It’s easy to retrieve when you know the key.
  • Associative array is one type of hash table.


  • Maps the key of any data type to an integer.
  • Hash function maps keys to int.
  • In Java, hash function is Object.hashCode()
  • Hash Collision occurs when more than one value has the same hashed value or hash code.

Load Factor

  • Load factor tells us how full the array is for example let’s say an array contains 5 user details backed by a hash table. It’s load factor would be 0.5.
  • Load factor is calculated by using Load Factor = Hash code of items / Capacity = Size / Capacity.
  • Load factor is used to decide when to resize the array backing the hash table.
  • There is lots of empty space when load factor is too low.
  • There will be high chances of hash collisions if load factor is too high.
  • Can play a role in determining the time complexity for the retrieval.

Adding an element to a Hash Table backed by an Array

  1. Provide a Key/Value pair.
  2. Use a hash function to hash the key to an int value.
  3. Store the value at the hashed key value - this is the index into the array.

Retrieving a value from a hash table

  1. Provide the key.
  2. Use the same hash function to hash the key to an int value.
  3. Retrieve the value stored at the hashed key value.


public class BehindJava {

	public static void main(String[] args) {

		Hashtable<Integer, String> map = new Hashtable<Integer, String>();
		map.put(1001, "Behind");
		map.put(1002, "Java");
		map.put(1003, "DataStructures");
		map.put(1004, "SpringBoot");

		for (Map.Entry m : map.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());


1004 SpringBoot
1003 DataStructures
1002 Java
1001 Behind