Hashtable
has two parameters :
initial_Capacity
and
load_Factor
.
Initial_Capacity
is the capacity when the hash table is created.
load_Factor
is a measure of how full the hash table is allowed to get before its capacity is automatically increased.
When the number of entries in the
Hashtable
exceeds the product of the
load Factor
and the current capacity, the capacity is increased by calling the
rehash()
method.
Constructors of the
Hashtable
class are :
Here is an example program using
Hashtable
class.
Hashtable Demo
import java.util.Hashtable;
class HashtableTest
{
public static void main(String arg[])
{
Hashtable<Integer, String> ranktable = new Hashtable<>(); // LINE A
Enumeration<Integer> e;
String playerName;
Integer rank;
ranktable.put(4, "Del Potro"); // LINE B
ranktable.put(1, "Rafael Nadal");
ranktable.put(2, "Novak Djokovic");
ranktable.put(5, "David Ferrer");
ranktable.put(3, "Stanislas Wawrinka");
e = ranktable.keys();
while (e.hasMoreElements()) // LINE C
{
rank = e.nextElement();
playerName = ranktable.get(rank);
System.out.println(rank + ": " + playerName);
}
}
}
OUTPUT5: David Ferrer
4: Del Potro
3: Stanislas Wawrinka
2: Novak Djokovic
1: Rafael Nadal
DESCRIPTIONAt LINE A
a new Hashtable
is created with Integer
as key and String
as value.
From LINE B
elements are added into the Hastable
.
At LINE C
the Hashtable
is iterated to display key-value pair with Enumeration
.
THINGS TO TRY
- Try to iterate over the
Hashtable
using keySet()
method.
- Replace
Stanislas Wawrinka
with Roger Ferrer
and display the elements in the Hashtable
. See that we can have duplicate values for two different keys.
- Check whether
10
is a key in the given Hashtable
or not. If it is, replace it with Jo-Wilfried Tsonga
.
- Change the rank (key) of
David Ferrer
to 6
, and see the output.