The perfect place for easy learning...

Java Programming

×

Topics List


Dictionary class in java





In java, the package java.util contains a class called Dictionary which works like a Map. The Dictionary is an abstract class used to store and manage elements in the form of a pair of key and value.

The Dictionary stores data as a pair of key and value. In the dictionary, each key associates with a value. We can use the key to retrieve the value back when needed.

🔔 The Dictionary class is no longer in use, it is obsolete.

🔔 As Dictionary is an abstract class we can not create its object. It needs a child class like Hashtable.

The Dictionary class in java has the following methods.

S. No. Methods with Description
1 Dictionary( )
It's a constructor.
2 Object put(Object key, Object value)

Inserts a key and its value into the dictionary. Returns null on success; returns the previous value associated with the key if the key is already exist.

3 Object remove(Object key)

It returns the value associated with given key and removes the same; Returns null if the key does not exist.

4 Object get(Object key)

It returns the value associated with given key; Returns null if the key does not exist.

5 Enumeration keys( )

Returns an enumeration of the keys contained in the dictionary.

6 Enumeration elements( )

Returns an enumeration of the values contained in the dictionary.

7 boolean isEmpty( )

It returns true if dictionary has no elements; otherwise returns false.

8 int size( )

It returns the total number of elements in the dictionary.

Let's consider an example program to illustrate methods of Dictionary class.

Example
import java.util.*;

public class DictionaryExample {

	public static void main(String args[]) {
		
		Dictionary dict = new Hashtable();
		
		dict.put(1, "Rama");
		dict.put(2, "Seetha");
		dict.put(3, "Heyansh");
		dict.put(4, "Varshith");
		dict.put(5, "Manutej");
		
		System.out.println("Dictionary\n=> " + dict);

		// keys()
        System.out.print("\nKeys in Dictionary\n=> ");
        for (Enumeration i = dict.keys(); i.hasMoreElements();) 
        { 
            System.out.print(" " + i.nextElement()); 
        } 

		// elements()
        System.out.print("\n\nValues in Dictionary\n=> ");
        for (Enumeration i = dict.elements(); i.hasMoreElements();) 
        { 
            System.out.print(" " + i.nextElement()); 
        } 
        
        //get() 
		System.out.println("\n\nValue associated with key 3 => " + dict.get(3));
		System.out.println("Value associated with key 30 => " + dict.get(30));
        
		//size()
		System.out.println("\nDictionary has " + dict.size() + " elements");
		
		//isEmpty()
		System.out.println("\nIs Dictionary empty?  " + dict.isEmpty());		
	}	
}

When we execute the above code, it produce the following output.

Dictionary class in java