Sunday, January 16, 2011

Using Hashtable in Java

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

public class HTDemo{

 public static void main(String []str){
  
  //Creating new Hatshtable 
  Hashtable ht = new Hashtable();
  
  //Adding objects of Entry class to Hashtable
  ht.put("Emma Watson",new Entry("Emma Watson","9741631235"));
  ht.put("Hugh Jackman",new Entry("Hugh Jackman","7353421215"));
  ht.put("Eric Bana",new Entry("Eric Bana","9471164719"));
  ht.put("Steve Jobs",new Entry("Steve Jobs","9132135451"));
  
  //Enumerating elements of Hashtable
  displayElements(ht);  
  ht.remove("Eric Bana"); 
  System.out.println("===============After removal==============");
  displayElements(ht);   
  
 }
 
 static void displayElements(Hashtable htable){
  Enumeration e = htable.keys(); 
  String key;
  Entry ent;
  while(e.hasMoreElements()){
  
   key = (String)e.nextElement(); 
   ent = (Entry)htable.get(key);   
   System.out.println("Name -> " + ent.getName());
   System.out.println("Phone -> " + ent.getPhone());
   System.out.println("-------------------------------");
  
  }
  
 }

}

class Entry{
 private String name;
 private String phone;
  
 Entry(){
  name="";
  phone="";
 }
 
 Entry(String nm,String pn){
  this.name = nm;
  this.phone = pn;
 }
 
 String getName(){
  return this.name;
 }
 
 String getPhone(){
  return this.phone;
 }
 
 void setName(String nm){
  this.name = nm;
 }
 
 void setPhone(String pn){
  this.phone = pn;
 } 

}