Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconSoftware Developmentbreadcumb forward arrow iconWhat is Hashtable in Java? Explained with Examples

What is Hashtable in Java? Explained with Examples

Last updated:
25th Jun, 2023
Views
Read Time
17 Mins
share image icon
In this article
Chevron in toc
View All
What is Hashtable in Java? Explained with Examples

What is Hashtable in Java?

Hashtable in java maps the keys to values. The Hashtable inherits the Dictionary class and implements the map interface. Any non-null object can be used as a value or a key. The objects used as keys in Hashtable must implement the “hashcode” method and the “equals” method.  It was a part of “original java.util” but got the power to implement the map interface in Java 2.

Hashtable is integrated into collections framework in java and is similar to HashMap except that Hashtable is synchronized. 

Hashtable in Java Features 

A hashtable in Java is a part of the Java collections framework and implements the Map interface. It is backwards compatible because it derives from the completely worthless and dated Dictionary class. After understanding hashmap and hashtable in Java, let’s look at some of its salient characteristics: 

  • Key-Based Hashtables: As opposed to arrays, a hashtable in Java only requires a key to find the value, which could be a different object. 
  • Dynamic Capacity: The hashmap and hashtable in Java are capable of holding greater numbers of elements than the internal array can manage by using chaining and linked lists. 
  • Performance: The Java hashtables performance may be O(n) in the worst-case scenario when you must traverse a linked list to find the correct value object due to collision, irrespective of knowing that hashtables are made for quick searches or O(1) searches (constant time search operations). 

Note: Since worst-case performance is now capped at O(logN), and JDK uses binary trees as opposed to linked lists from Java 8, performance has been significantly enhanced. 

Ads of upGrad blog
  • Application: Maps or pairs of key-value items are stored in hashtables. As a result, it might be used to store client information, library books, or other documents. 
  • Sorting: A hashtable can’t be sorted. However, data that is sorted can be obtained and extracted by classifying the hash table’s list of keys and then extracting values via a LinkedHashMap or TreeMap to retrieve the values in the proper order. 
  • Collision: Collisions can happen in hashtables because distinct data items may collide and be related to the same bucket. That’s because their hash values clash. Different collision avoidance strategies, such as open addressing or chaining, can be used to tackle this. 
  • Synchronization: The hashtable class is thread-safe because it is synchronized. More than one thread can’t get to the Hashtable class instance at once. Because of this, its operations are slower than Java’s HashMaps. 

Note: Using HashMap rather than Hashtable in Java is advised if a thread-safe implementation isn’t necessary. 

Java Hashtable Example

import java.util.*;  
class Hashtable1{  
 public static void main(String args[]){  
  Hashtable<Integer,String> hm=new Hashtable<Integer,String>();

  hm.put(200,"Rohan");  
  hm.put(202,"Rohit");  
  hm.put(201,"Raunak");  
  hm.put(203,"Ramesh");

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

Output

203 Ramesh
202 Raunak
201 Rohit
200 Rohan

Here is another Java hashtable example for the remove() operation: 

import java.util.*;  
public class Hashtable2 {  
   public static void main(String args[]) {  
  Hashtable<Integer,String> map=new Hashtable<Integer,String>();        
     map.put(200,"Rohan");    
     map.put(202,"Raunak");   
     map.put(201,"Rohit");    
     map.put(203,"Ramesh");    
     System.out.println("Before remove: "+ map);    
       // Remove value for key 202  
       map.remove(202);  
       System.out.println("After remove: "+ map);  
   }      
}

Output:

Before remove: {203=Ramesh, 202=Raunak, 201=Rohit, 200=Rohan}
After remove: {203=Ramesh, 201=Rohit, 200=Rohan}

With these two Java hashtable examples as well as the understanding of hashtable’s salient features, you should now have a solid grasp of this Java concept. 

Check out our free technology courses to get an edge over the competition.

Hierarchy of Hashtable in Java

 

Source:

The direct subclasses of Hashtable in java are Properties and UIDefaults.

  • Hashtable in java implements Serializable and Cloneable.
  • Hashtable in java extends Dictionary<K,V>.

Explore our Popular Software Engineering Courses

Class Declaration- Hashtable in Java

The declaration for java.util.Hashtable class is:

public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Cloneable, Serializable

Class Parameters- Hashtable in Java 

The parameters for java.util.Hashtable class are:

  • K: It stands for the different key types maintained by this map.
  • V: It stands for mapped value types.

Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs or Masters Programs to fast-track your career.

Working of Hashtable in Java

Hashtable is a data structure that stores keys or value pairs and is an array of buckets. The determination of the mapping of a bucket of keys or value pairs is achieved using the hashCode() method. 

This hashcode is a non-negative integer that is equal for equal objects. This may or may not be equal for unequal objects. The Hashtable in Java uses the equals() method to check whether two objects are equal or not.

Thus, the hash function determines the location for a given key in the bucket list. In simple words, an object is used as a key, and value is linked to the key. The hashing of key results in a hashcode. This hashcode represents the index at which values are stored in the Hashtable.

What is Collision in Hashtable in Java?

When two unequal objects have the same hashcodes in Hashtable, the condition is termed as collision. An array of lists is used to resolve collision in Hashtable. It is resolved by storing the pairs mapped to a single bucket in a list. This list reference is then stored in the array index.

In case of hash collision, the multiple entries in a single bucket must be searched sequentially.

What are the Parameters affecting the Performance of Hashtable in Java?

The main parameters that affect the performance of any instance of Hashtable are:

  • Initial Capacity:

The number of buckets in a Hashtable is called its capacity. The capacity of the Hashtable at the time of its creation is its initial capacity. It controls a tradeoff between wasted space and rehashes operations’ requirements. Thus setting high values of initial capacity wastes space in Hashtable. If the initial capacity is greater than the maximum number of entries, no rehash operations are possible.

  • Load Factor:

The measure of how full the Hashtable is allowed before its capacity is automatically increased is termed as the load factor of Hashtable in java. The default load factor value is 0.75, and it allows a good tradeoff between time and space costs. With an increase in load factor, the time cost to lookup an entry is increased, and space overhead decreases.

Constructors- Hashtable in Java

We need to import Hashtable in java from java.util.Hashtable. The different ways in which Hashtable can be created in java are:

  • Hashtable():

It creates an empty Hashtable with an initial capacity of 11 and the default load factor of 0.75. It can be explained using the following example.

Hashtable<K,V> ht = new Hashtable<K,V> ();

Input:

Source: 

Output:

Source: 

  • Hashtable(int initialCapacity):

It creates a Hashtable with a default load factor of 0.75. The initial capacity is defined by the initialCapacity. It can be explained using the following example.

Hashtable<K,V> ht = new Hashtable<K,V> (int initialCapacity);

Input:

Source: 

Output:

Source: 

  • Hashtable(int size, float fillRatio):

It creates a Hashtable whose fill ratio is defined by fillRatio. It defines that how full a Hashtable can be before it is resized upwardly. The initial size in this constructor is specified by “size.” It can be explained using the following example.

Hashtable<K,V> ht = new Hashtable<K,V> (int size, float fillRatio);

Input:

Source: 

Output:

Source: 

  • Hashtable(Map<? Extends K,? extends V>m)

It creates a Hashtable that is initialized with the elements of “m.” It can be explained using the following example.

Hashtable<K,V> ht = new Hashtable<K,V> (Map m);

Input:

Output:

Source: 

Different Methods of Hashtable in Java

The different methods in the Java Hashtable class and their description are as below:

  • void clear() Method:

This method is used to reset the Hashtable.

  • Enumeration elements() Method:

An enumeration of the values in the Hashtable is returned by this method.

  • Object clone() Method:

This method returns a shallow copy of the Hashtable.

  • Set<Map.Entry<K,V>> entrySet() Method:

To return a set view of the mappings contained in the map, this method is used.

  • boolean equals(Object o) Method:

This method is used to compare the specified object within the hashmap of the table.

  •  int hashCode() Method:

This method returns the hash code value for the map.

  • Set<K> keySet() Method:

This method returns a Set view of the keys present in the map.

  • V put(K key, V value) Method:

This method inserts the defined value with the defined key in the Hashtable.

  • boolean remove(Object key, Object value) Method:

This method removes the specified values with the associated specified keys from the Hashtable.

  • V replace(K key, V value) Method:

This method replaces the defined value for a defined key.

  • String toString()Method:

This method returns the representation of the objects in Hashtable.

  • Collection values() Method:

This method returns a collection view of the values present in the map.

  • boolean contains(Object value) Method:

It returns to true if there is some value equal to the value that exists from the Hashtable. It otherwise returns false.

  • boolean containsValue(Object value) Method:

It returns true if there is some value equal to the value that exists from the Hashtable. It otherwise returns false.

  • boolean containsKey(Object key) Method:

It returns true if some key equal to the key exists in the Hashtable. It otherwise returns false.

  • boolean isEmpty() Method:

It returns true if the Hashtable is empty. It otherwise returns to false if it contains at least one key.

  • protected void rehash() Method:

This method is used to increase the size of the Hashtable and rehashes all of its keys.

  • V get(Object key) Method:

It returns the object that contains the value attached with the key.

  • V remove(Object key) Method:

This method is used to remove the key and its value. This method returns the value defined with the key.

In-Demand Software Development Skills

  • int size() Method:

It returns to the number of entries present in the Hashtable.

  • V compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction) Method:

This method computes the mapping for any specified key. It also computes its current mapped value and goes to null if there is no current mapping.

  • V computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction) Method:

This method computes its value using the given mapping function if the specified key is not already associated with a value or to the condition in which it is mapped to null). It also enters it into this map unless it achieves null.

  • V computeIfPresent(K key, BiFunction<? super K,? super V,? extends V> remappingFunction) Method:

It further computes its current mapped value if the value for the specified key is present and is non-empty, along with its new mapping.

  • void forEach(BiConsumer<? super K,? super V> action) Method:

This method performs the given action for each entry in the map until all entries are done.

  • V getOrDefault(Object key, V defaultValue) Method:

This method returns to the value to which the defined key is mapped. It also returns to defaultValue if the map contains no mapping for the key.

  • V merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction) Method:

This method associates a defined key with the given non-null value if it is not already associated with a value or is associated with null.

  • boolean replace(K key, V oldValue, V newValue):

This method replaces the old value with the new value for the specified key.

  • void putAll(Map<? extends K,? extends V> t)) Method:

This method copies all the key-value pair from the map to the Hashtable.

  • V putIfAbsent(K key, V value) Method:

This method associates the specified key with the given value. It returns null if it is already associated with a value (or is mapped to null), else it returns the current value.

  • void replaceAll(BiFunction<? super K,? super V,? extends V> function) Method:

It replaces the entry’s value with the result of introducing the given function on that entry only. It is done until all entries processor until the condition in which the function throws an exception.

Different Operations on Hashtable in Java

The different operations on Hashtable can be performed in the following ways:

  • Adding Elements:

The put() method is used to add an element to the Hashtable. Internally, a separate hash is generated for each element. The elements are indexed based on this hash only to make it more efficient. The insertion order is not retained in the Hashtable. For example:

Input:

Source: 

Output:

Source: 

  • Changing Elements:

If you want to change an element after adding, it can be done by again the element by using put(). The elements in a Hashtable are indexed using the keys. Thus, the key’s value can be changed by inserting the updated value of the key. For example:

 Input:

Source: 

Output:

Source:

  • Removing Elements:

The remove() method is used to remove an element from the map. It takes the key values and removes the mapping for a key from this map if it is present. For example:

Input:

Source:

Output:

Source:

  • Traversal of a Hashtable:

An advanced “for loop” is used in Hashtable in java to iterate the table. For example:

Input:

Source: 

Output:

Source:

Programs- 

  • Program illustrating simple Hashtable in Java.

Input:

Source: 

Output:

Source: 

  • Program illustrating several of the methods supported by Hashtable in Java

Input:

Source:

Output:

Source: 

  • Program illustrating Java Hashtable Book

Input:

Source: 

Output:

Source:

  • Program illustrating Java Hashtable remove()

Input:

Source:

Output:

Source:

  • Program illustrating Java Hashtable putifAbsent()

Input:

Source:

Output:

Source: 

  • Program illustrating Java Hashtable getOrDefault()

Input:

Source

Output:

Source 

  • Program illustrating key-value pairs using enumeration.

Input:

Source

Output:

Ads of upGrad blog

Source

Read our Popular Articles related to Software Development

Points to Remember- Hashtable in Java

  • It contains unique elements.
  • It contains values based on the key.
  • It is an array of a list, and each list is known as a bucket.
  • The hashcode() method is called to identify the position of the bucket.
  • The default capacity of Hashtable in java is 11 initially.
  • The loadFactor of the Hashtable class is 0.75.
  • Hashtable in java is synchronized.
  • Only non-null value can be used as a key or value.
  • It doesn’t guarantee any order.
  • The enumerator in Hashtable in java is not fail-fast.

Amid increased conversations around crypto and Blockchain technology, if you wish to educate yourself professionally on the topic, then upGrad’s Executive Post Graduate Programme in Software Development – Specialisation in Blockchain under IIIT- Bangalore is the right choice for you!

Profile

Pavan Vadapalli

Blog Author
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and long term technology strategy.