본문 바로가기

Java/__Base

Java - Hashtable Example

1. Hashtable example with Enumeration

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

public class HashTableExample {

    public static void main(String[] args) {

        Hashtable<Integer,String> hTable=new Hashtable<Integer,String>();

        //adding or set items in Hashtable by put method key and value pair
        hTable.put(new Integer(2), "Two");
        hTable.put(new Integer(1), "One");
        hTable.put(new Integer(4), "Four");
        hTable.put(new Integer(3), "Three");
        hTable.put(new Integer(5), "Five");

        // Get Hashtable Enumeration to get key and value
        Enumeration em=hTable.keys();

        while(em.hasMoreElements())
        {
            //nextElement is used to get key of Hashtable
            int key = (Integer)em.nextElement();

            //get is used to get value of key in Hashtable
            String value=(String)hTable.get(key);

            System.out.println("Key :"+key+"  value :"+value);
        }
    }
}
2. Hashtable example with Enumeration

import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;
import java.util.Map;

public class HashTableJava {

    public static void main(String[] args) {

        Hashtable<Integer,String> hTable=new Hashtable<Integer,String>();

        hTable.put(new Integer(2), "Two");
        hTable.put(new Integer(1), "One");
        hTable.put(new Integer(4), "Four");
        hTable.put(new Integer(3), "Three");
        hTable.put(new Integer(5), "Five");

        Set s =hTable.entrySet();

        Iterator i=s.iterator();

        while(i.hasNext())
        {
            Map.Entry m=(Map.Entry)i.next();

            int key = (Integer)m.getKey();
            String value=(String)m.getValue();

            System.out.println("Key :"+key+"  value :"+value);
        }
    }
}
Output

Key :5 value :Five
Key :4 value :Four
Key :3 value :Three
Key :2 value :Two
Key :1 value :One