Menu
Topics Index
...
`

Hashtable Demo - Java Example Program


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);
        }    
    }
}
OUTPUT

5: David Ferrer
4: Del Potro
3: Stanislas Wawrinka
2: Novak Djokovic
1: Rafael Nadal

DESCRIPTION

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

© meritcampus 2019

All Rights Reserved.

Open In App