Hashtable in Java
Introduction
Some of the characteristics of a hashtable are explained below:
- A hashtable stores {key, value} pair in a hashtable.
- It is similar to a hashmap the only difference is hashtable is synchronized whereas a hashmap doesn’t.
- The Hashtable class has a default capacity of 11 whereas its load factor is 0.75.
- The Hashtable class provides a not fail-fast enumeration while a HashMap doesn’t offer any enumeration.
Java provides us Hashtable class in Java that maps a key to value. A hashtable in Java can be declared using the following syntax:
Syntax:
public class Hashtable<U,V> extends Dictionary<U,V> implements Map<U,V>, Cloneable, Serializable |
Parameters:
U: It specifies the type of key of the hashtable |
Creating a hashtable in Java
The hashtable class is defined under the java.util.Hashtable package. Let us see the working of a hashtable with the help of the following example:
Source Code:
import java.io.*; |
Output:
Methods on hashtable
The hashtable class provides us numerous methods that can be implemented on hashtable. Some of these methods are explained below:
put() method
This method is used to insert elements in a defined hashtable. This function has the following syntax:
Syntax:
hashtable.put(key, value) |
Parameters:
key: The corresponding key of the element |
Source Code:
import java.io.*; |
Output:
remove() method
This method is used to remove an element from a defined hashtable. This function has the following syntax:
Syntax:
hashtable.remove(key) |
Parameter:
key: The key of the element to be removed |
Now consider a program given below:
Source Code:
import java.io.*; |
Output:
Traversing a hashtable
We can use advance for loop to iterate over a hashtable in Java. Consider a program below iterating over a hashtable:
Source Code:
import java.io.*; |
Output:
Internal working of a hashtable
A hashtable datastructure consist of array of buckets that stores key and value pairs inside them. In order to determine which bucket should a ke/value map, it makes the use of hashCode() method.
Internally, a hash function is also used to determine the location for a given key in the list of buckets. Most of the time, a hashcode is a non-negative integer that is surely equal for equal objects but may or may not be equal for unequal objects. Internally, to check whether two object are equal or not, hashtable makes the use of equals() method.
Conclusion
In this article, we discussed about what are hashtables, hashtable methods, hashtables internal working. I hope this article will help to strengthen your knowledge in the field of Java.