Menu
Topics Index
...
`


Collections Framework > Legacy Classes and Interfaces >
Siva Nookala - 01 Apr 2016
The Dictionary class is the abstract parent of classes like Java Hashtable, which maps keys to values. Every key and every value is an object. In any one Dictionary object, every key is associated with at most one value.

Dictionary Constructor:
ConstructorDescription
Dictionary()Creates dictionary.

Dictionary Methods:
MethodDescription
Enumeration elements()Returns an enumeration of the values in this dictionary.
Object get(Object key)Returns the value to which the key is mapped in this dictionary.
boolean isEmpty()Tests if this dictionary has no keys.
Enumeration keys()Returns an enumeration of the keys in this dictionary.
Object put(Object key, Object value)Maps the specified key to the specified value in this dictionary.
Object remove(Object key)Removes the key (and its corresponding value) from this dictionary.
int size()Returns the number of entries (distinct keys) in this dictionary.

Dictionary
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() + " ");
    
    }
}
OUTPUT

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

DESCRIPTION

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.

THINGS TO TRY
  • At LINE A, replace 2by 8and see the output where Nishanis retrieved from the dictionary.
  • At LINE B, replace 4 by 7 and see the output where Ramis removed from the dictionary.

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App