How do I create a Hashtable and iterates its contents?

The code snippet shows you how to create and instance of Hashtable that stores Integer values using a String keys. After that we iterates the elements of the Hashtable using the Enumeration interface.

package org.kodejava.example.util;

import java.util.Enumeration;
import java.util.Hashtable;

public class HashtableDemo {
    public static void main(String[] args) {
        //
        // Creates an instance of Hashtable
        //
        Hashtable numbers = 
                new Hashtable();
        numbers.put("one", 1);
        numbers.put("two", 2);
        numbers.put("three", 3);

        // 
        // Returns an enumeration of the keys in this Hashtable
        //
        Enumeration keys = numbers.keys();
        while (keys.hasMoreElements()) {
            // 
            // Returns the next element of this enumeration if this
            // enumeration object has at least one more element to 
            // provide
            String key = keys.nextElement();
            System.out.println("Key: " + key + ", Value: " + 
                    numbers.get(key));
        }
    }
}
Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.
Wayan Saryada

Leave a Reply