Basics of HashTable in Java

We started with Array’s in Java and moved to ArrayList, today we would be focusing on Hash Table’s in Java. Further we would be comparing Hast Table with Hash Map.

HashTable in Java example
HashTable for happy living 

What is a Hash Table?
A Hashtable (is a data structure) is similar to ArrayList but here we don’t directly use Index to access elements but instead use Key to store a given value. It works on the principle of Key-Value pairs (like a dictionary inVbscript.).Such that each value is accessed by a corresponding Key.

In simple terms, Hashtables work by mapping a key to a value.

Any non-null object can be used as a key or as a value.
Principle behind HashTable:-
A hash table stores data inthe form of Key-value pairs.It is made up of two parts: an array (the actual table where the data to be searched is stored called as Buckets) and a mapping function, known as a hash function. The hash function is most important part, as it is  responsible for mapping from the given Key to an index for storing Key-value pairs in the Array. 

In other words, the hash function provides a way for assigning numbers to the input data such that the data can then be stored at the array index corresponding to the assigned number.

HashTable Example Java

Hash function assigns an hash code(index) based on two factors the key and the range of the bucket(thus it calculates index = Hash function(Key, Range of Array)).

Data is placed into a hashtable through the put method, and can be accessed using the get method.

When we pass Key and Value object  to put(key, value) method it calls the   hash Function on Key object and applies returned hash code into its own 
hashing function to find a bucket location for storing Entry object, vital thing is that, in Hashtable Java stores both key and value object in Bucket.

A hash function doesn’t guarantee that every input will map to a different output. There is always the chance that two inputs will hash to the same output. Meaning more than one key,value pairs can be indexed to the same array location.This indicates that both elements should be inserted at the same place in the array, and this is impossible. This phenomenon is known as a collision.It can be avoided by various techniques like chaining,linked list. we are not discussing Collision in HastTable in this post.

It can be created using one of the following four constructors;

Creates an Empty Hash table with a default initial capacity(11) and load factor (0.75). 

Means array size is 11 and when it is 75% occupied its array size would increase automatically to accomdate new key,value pairs.

2.Hashtable(int initialCapacity)
creates a hash table that has given initial size specified by InitialCapacity

3.Hashtable(int initialCapacity, float loadFactor)
Creates a hash table that has an initial size specified by intial capacity and a loadFactor decides when to automatically increase the size of the Hashtable.

4.HashTable(Map m)
Creates an Hashtable with a Given Map m.

1.Load factor Default value is .75 , That if the Hashtable is 3/4 th full then the size of the Hashtable is increased, this is called Rehashing. We can force hashtable to expand only when it is completely full by making Load factor to 1.0 but it is not recommended as it effects performance of hashtable by increasing probability of collision (Meaning same hashcode for different keys)

2.We would get “IllegalArgumentException“- if the initial capacity is less than zero, or if the load factor is negative.

3.Duplicate and Null Key values are not allowed in Hash Table thus an Hashtables never contain items with duplicate keys.

Important Methods:-
Get:-Returns the Value for the Given Key in the HashTable, null if this HashTable contains no mapping for the key

Put: – Used for creating a Mapping between a Given Key and Value. Meaning adding Key-Value pairs to HashTable

Size: – Returns the count of keys in Hashtable

Keys: – Returns an enumeration (collection of objects) of the keys in hashtable.

Clone: – Creating a replica of HashTable

1. Using Put and Get method to create and retrieve data from a HashTable
public static void main(String args[]) {

// Creating Hashtable for example
Hashtable companies = new Hashtable();

// Java Hashtable example to put object into Hashtable
// put(key, value) is used to insert object into map
companies.put(“Google”, “United States”);
companies.put(“Nokia”, “Finland”);
companies.put(“Sony”, “Japan”);

System.out.println(companies );
// Java Hashtable example to get Object from Hashtable
// get(key) method is used to retrieve Objects from Hashtable

2.Using Size method to find the size of HashTable,clone the hashtable and clear the hashTable
// How to find size of Hashtable in Java
// use hashtable.size() method to find size of hashtable in Java
System.out.println(“Size of hashtable in Java: ” + companies.size());

Difference between Hash Table and Hash Map?
The HashMap  is equivalent to Hashtable, except that it is non synchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn’t allow nulls).

Synchronized means only one Thread can modify a hash table at one point of time. Meaning that any thread before performing an update on a Hashtable will have to acquire a lock on the object while others will wait for lock to be released.

import java.util.Hashtable;

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

        Hashtable hashtableobj = new Hashtable();
        hashtableobj.put(“Alive is “, “awesome”);
        hashtableobj.put(“Love”, “yourself”);
        System.out.println(“Hashtable object output :”+ hashtableobj);


        HashMap hashmapobj = new HashMap();
        hashmapobj.put(“Alive is “, “awesome”);  
        hashmapobj.put(“Love”, “yourself”); 
        System.out.println(“HashMap object output :”+hashmapobj);   


Leave a Reply

Your email address will not be published. Required fields are marked *