Basics of HashTable in Java – User friendly Tech help

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.
n

n

n

n

n

n

n

n

n

HashTable for happy living 

n

What is a Hash Table?

n

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.
n

n

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

n

nNote:-

n

Any non-null object can be used as a key or as a value.

n

Principle behind HashTable:-

nA 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. 
n
nIn 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. n

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)).
n
nData is placed into a hashtable through the put method, and can be accessed using the get method.
n
nWhen 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 
nhashing 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.
n
nNote:- 
nA 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.

n

Syntax:-

n

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

n

1.Hashtable()

n

Creates an Empty Hash table with a default initial capacity(11) and load factor (0.75). 
n
nMeans array size is 11 and when it is 75% occupied its array size would increase automatically to accomdate new key,value pairs.
n

n

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

n

3.Hashtable(int initialCapacity, float loadFactor)

n

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.
n

n

4.HashTable(Map m)

n

Creates an Hashtable with a Given Map m.

n

Note:-
n1.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)
n

n

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

n

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

n

Important Methods:-

n

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

n

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

n

Size: – Returns the count of keys in Hashtable
n

n

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

n

Clone: – Creating a replica of HashTable

n

Example:-

n

1. Using Put and Get method to create and retrieve data from a HashTable

n

public static void main(String args[]) {

n

// Creating Hashtable for example

n

Hashtable companies = new Hashtable();

n

// Java Hashtable example to put object into Hashtable

n

// put(key, value) is used to insert object into map

n

companies.put(“Google”, “United States”);

n

companies.put(“Nokia”, “Finland”);

n

companies.put(“Sony”, “Japan”);

n

System.out.println(companies );

n

// Java Hashtable example to get Object from Hashtable

n

// get(key) method is used to retrieve Objects from Hashtable

n

companies.get(“Google”);

n

2.Using Size method to find the size of HashTable,clone the hashtable and clear the hashTable

n

// How to find size of Hashtable in Java

n

// use hashtable.size() method to find size of hashtable in Java

n

System.out.println(“Size of hashtable in Java: ” + companies.size());

n

table.clear();

n

Difference between Hash Table and Hash Map?

n

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).

n

Note:-

n

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.

n

import java.util.Hashtable;
n
n
npublic class HashMapHashtableExample {
n    
n    public static void main(String[] args) { 

n

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

n

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

n

n }

n

Java Concepts
nExplore Selenium

Was this article helpful?
YesNo

Similar Posts