Home  >  Core Java

Hashtable Java Example

By Arvind Rai, August 16, 2013
Hashtable works on the basis of hashtable. Hashtable maps not null key and value. The object which is being created as key, must implements hashCode() and equals() methods. Hashtable works on the basis of initial capacity and load factor. When Hashtable is created, at that time the size of Hashtable is initial capacity. Load factor is that before increasing the size of Hashtable, how full Hashtable should be.

Iterate Hashtable

Hashtable can be iterated through Entry and Enumeration. In below example we will see both approaches.

HashtableDemo.java
package com.util;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Map.Entry;
import java.util.Set;
public class HashtableDemo {
    public static void main(String[] args) {
        Hashtable<Integer, String> ht = new Hashtable<Integer, String>();
        ht.put(1,"A");
        ht.put(2,"B");
        ht.put(3,"C");
        Set<Entry<Integer,String>> set = ht.entrySet();
        
        //iterate through Entry 
        for(Entry<Integer,String> en: set){
            System.out.println(en.getKey());
            System.out.println(en.getValue());
        }
        
        //iterate through Enumeration
         Enumeration<Integer> enm = ht.keys();
         while(enm.hasMoreElements()){
             System.out.println(ht.get(enm.nextElement()));
         }
    }
}
 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us