The following program demonstrates An Example of Hashtable Class in Java.

In the following program, we create a Hashtable with specified key-value pairs. While the keys are of the type Staff, which is a user-defined type. On the other hand, the values are of the Double type. So, this Hashtable represents the Staff as the key and their salaries as the values.

package com.maps;
import java.util.*;

public class HashtableDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Hashtable<Staff, Double> htb=new Hashtable<Staff, Double>();
		htb.put(new Staff(101, "Jim"), 12000.0);
		htb.put(new Staff(102, "Jill"), 14000.0);
		htb.put(new Staff(103, "Joe"), 24000.0);
		htb.put(new Staff(104, "Joe"), 34000.0);
		htb.put(new Staff(102, "Jill"),5000.0);
		htb.put(new Staff(101, "Jim"), 19000.0);
		
		System.out.println("Elements in Hashtable: ");
		Set entrySet=htb.entrySet();
		Iterator it=entrySet.iterator();
		while(it.hasNext())
		{
			Map.Entry<Staff, Double> me=(Map.Entry<Staff, Double>)(it.next());
			System.out.println("Key: "+me.getKey()+", Value: "+me.getValue());
		}
		
		System.out.println("Displaying All Salaries...");
		Enumeration names=htb.keys();
		while(names.hasMoreElements())
		{
			Staff s=(Staff)names.nextElement();
			System.out.println(s+", Salary:"+htb.get(s));
		}
	}
}
/*
 * 
 */
class Staff 
{
	int staff_id;
	String sname;

	public Staff(int staff_id, String sname) {
		super();
		this.staff_id = staff_id;
		this.sname = sname;
	}
	public int getStaff_id() {
		return staff_id;
	}
	public void setStaff_id(int staff_id) {
		this.staff_id = staff_id;
	}
	public String getSname() {
		return sname;
	}
	public void setSname(String sname) {
		this.sname = sname;
	}
	@Override
	public String toString() {
		return "Staff Details: [staff_id=" + staff_id + ", sname=" + sname + "]";
	}	
}

Output

Demonstrating An Example of Hashtable Class in Java
Demonstrating An Example of Hashtable Class in Java

Further Reading

Java Practice Exercise

programmingempire

Princites