Introduction
Dictionary in Java is an abstract class that is a part of java.util package. It stores key-value pairs and works very similar to a Map. The Dictionary class is a direct superclass of HashTable, implemented by the Map interface. (See Data Structures)
Every key or value of a dictionary is an object and must not be null. Dictionary key objects have at most one value associated with them, using which elements can be accessed. Dictionary() is the sole constructor of the Dictionary class.
Declaration:
public abstract class Dictionary extends Object
Initialisation:
Dictionary dict_name = new Hashtable();

Dictionary Syntax in Java
public abstract class Dictionary<K,V> {
// Abstract methods and implementation
}
Dictionary Constructor
The Dictionary class constructor creates an empty dictionary. It's an abstract class that maps keys to values, though it's now obsolete - HashMap is the modern alternative.
Note: The Dictionary class has been deprecated since Java 1.2. It's recommended to use Map implementations like HashMap or TreeMap instead, as they provide better functionality and are part of the modern Collections Framework.
Dictionary Class Methods in Java
Method | Type | Description |
---|---|---|
isEmpty( ) | abstract Boolean | It checks if the dictionary has no key-value pairs. |
put( K key, V value ) | abstract V | It maps the specified key and value in the dictionary and returns the previous value of the key or null if absent. |
size( ) | abstract int | It returns the number of entries in the dictionary. |
get( Object key ) | abstract V | It returns the value of the specified key. |
remove( Object key ) | abstract V | It removes the specified key and its value from the dictionary and returns the value or null if absent. |
keys( ) | abstract Enumeration<K> | It returns an enumeration of all the keys in the dictionary. |
elements( ) | abstract Enumeration<V> | It returns an enumeration of all the values in the dictionary. |
Also read, Duck Number in Java and Hashcode Method in Java
Example:
The following example shows the use of all the functions of the Dictionary class mentioned in the table.
Output:
Keys in Dictionary : Australia Europe
Values in Dictionary : A E
Value at key = E : Europe
Value at key = R : null
Removing key E: Europe
Is the dictionary empty? false
Size of Dictionary : 1
The methods hasMoreElements() and nextElement() are used to check for more constants in the enumeration and get the next value respectively. Trying to get the value of key ‘R’ returns null as it does not exist in the dictionary. Try it on java online compiler.