CODE
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Hashtable;
class DictionaryMethods
{
public static void main(String arg[])
{
Dictionary d = new Hashtable();
d.put("8", "Nishan"); // Adds key and value to dictionary
d.put("5", "Om");
d.put("2", "Santosh");
d.put("7", "Ram");
d.put("4", "Amar");
System.out.println("The dictionary contains : " + d); // Displays dictionary
System.out.println("The size of dictionary d is : " + d.size());
System.out.println("The value at key 2 : " + d.get("2")); // LINE A
System.out.println("Is the dictionary is empty : " + d.isEmpty());
System.out.println("The value of key 4 while removing : " + d.remove("4")); // LINE B
System.out.println("After removing, dictionary : " + d);
System.out.print("The keys of dictionary are : ");
for (Enumeration e = d.keys(); e.hasMoreElements();) // Enumeration elements
System.out.print(e.nextElement() + " ");
}
}
The dictionary contains : {5=Om, 4=Amar, 2=Santosh, 8=Nishan, 7=Ram}
The size of dictionary d is : 5
The value at key 2 : Santosh
Is the dictionary is empty : false
The value of key 4 while removing : Amar
After removing, dictionary : {5=Om, 2=Santosh, 8=Nishan, 7=Ram}
The keys of dictionary are : 5 2 8 7
In this program, a dictionary is created by using Hashtable
and 5 names are inserted into dictionary with keys using put
method. The size, get, isEmpty, remove, Enumeration
and keys
methods are used.
LINE A
, replace 2
by 8
and see the output where Nishan
is retrieved from the dictionary.LINE B
, replace 4
by 7
and see the output where Ram
is removed from the dictionary.