What is Hashtable in Java? Explained with Examples
Updated on Jul 03, 2023 | 17 min read | 7.6k views
Share:
For working professionals
For fresh graduates
More
Updated on Jul 03, 2023 | 17 min read | 7.6k views
Share:
Table of Contents
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.
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:
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.
Note: Using HashMap rather than Hashtable in Java is advised if a thread-safe implementation isn’t necessary.
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.
The direct subclasses of Hashtable in java are Properties and UIDefaults.
The declaration for java.util.Hashtable class is:
public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Cloneable, Serializable
The parameters for java.util.Hashtable class are:
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.
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.
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.
The main parameters that affect the performance of any instance of Hashtable are:
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.
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.
We need to import Hashtable in java from java.util.Hashtable. The different ways in which Hashtable can be created in java are:
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:
Output:
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:
Output:
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:
Output:
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:
The different methods in the Java Hashtable class and their description are as below:
This method is used to reset the Hashtable.
An enumeration of the values in the Hashtable is returned by this method.
This method returns a shallow copy of the Hashtable.
To return a set view of the mappings contained in the map, this method is used.
This method is used to compare the specified object within the hashmap of the table.
This method returns the hash code value for the map.
This method returns a Set view of the keys present in the map.
This method inserts the defined value with the defined key in the Hashtable.
This method removes the specified values with the associated specified keys from the Hashtable.
This method replaces the defined value for a defined key.
This method returns the representation of the objects in Hashtable.
This method returns a collection view of the values present in the map.
It returns to true if there is some value equal to the value that exists from the Hashtable. It otherwise returns false.
It returns true if there is some value equal to the value that exists from the Hashtable. It otherwise returns false.
It returns true if some key equal to the key exists in the Hashtable. It otherwise returns false.
It returns true if the Hashtable is empty. It otherwise returns to false if it contains at least one key.
This method is used to increase the size of the Hashtable and rehashes all of its keys.
It returns the object that contains the value attached with the key.
This method is used to remove the key and its value. This method returns the value defined with the key.
It returns to the number of entries present in the Hashtable.
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.
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.
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.
This method performs the given action for each entry in the map until all entries are done.
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.
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.
This method replaces the old value with the new value for the specified key.
This method copies all the key-value pair from the map to the Hashtable.
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.
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.
The different operations on Hashtable can be performed in the following ways:
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:
Output:
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:
Output:
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:
Output:
An advanced “for loop” is used in Hashtable in java to iterate the table. For example:
Input:
Output:
Output:
Output:
Output:
Output:
Output:
Output:
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!
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources