The Wayback Machine - https://web.archive.org/web/20240914011159/https://www.geeksforgeeks.org/java-util-dictionary-class-java/
Open In App

Java.util.Dictionary Class in Java

Last Updated : 09 Apr, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The java.util.Dictionary class in Java is an abstract class that represents a collection of key-value pairs, where keys are unique and are used to access the values. It was part of the Java Collections Framework introduced in Java 1.2 but has been largely replaced by the java.util.Map interface since Java 1.2.

The Dictionary class is an abstract class and cannot be instantiated directly. Instead, it provides the basic operations for accessing the key-value pairs stored in the collection, which are implemented by its concrete subclass java.util.Hashtable.

The Dictionary class defines the following methods:

  1. get(Object key): Returns the value associated with the specified key in the dictionary, or null if the key is not found.
  2. put(Object key, Object value): Inserts a key-value pair into the dictionary. If the key already exists, its corresponding value is
  3. replaced with the new value, and the old value is returned. If the key is new, null is returned.
  4. remove(Object key): Removes the key-value pair associated with the specified key from the dictionary, and returns its value. If the key is not found, null is returned.
  5. size(): Returns the number of key-value pairs stored in the dictionary.
  6. isEmpty(): Returns true if the dictionary is empty, and false otherwise.
    elements(): Returns an enumeration of the values stored in the dictionary.
  7. keys(): Returns an enumeration of the keys stored in the dictionary.

Here’s an example of using the Dictionary class:

Java




import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Hashtable;
 
public class DictionaryExample {
    public static void main(String[] args)
    {
        Dictionary<String, Integer> dict= new Hashtable<>();
        dict.put("Alice", 25);
        dict.put("Bob", 30);
        dict.put("Charlie", 35);
 
        System.out.println(dict.get("Bob")); // 30
 
        int oldValue = dict.put("Charlie", 40);
        System.out.println(oldValue); // 35
 
        dict.remove("Alice");
 
        System.out.println(dict.size()); // 2
 
        Enumeration<String> k = dict.keys();
        while (k.hasMoreElements()) {
            String key = k.nextElement();
            System.out.println("Key: " + key + ", Value: "
                               + dict.get(key));
        }
    }
}


Output

30
35
2
Key: Bob, Value: 30
Key: Charlie, Value: 40

util.Dictionary is an abstract class, representing a key-value relation and works similar to a map. Given a key you can store values and when needed can retrieve the value back using its key. Thus, it is a list of key-value pair. 

Declaration 

public abstract class Dictionary extends Object

Constructors: 
Dictionary() Sole constructor. 

The java.util.Dictionary class is a class in Java that provides a key-value data structure, similar to the Map interface. It was part of the original Java Collections framework and was introduced in Java 1.0.

However, the Dictionary class has since been considered obsolete and its use is generally discouraged. This is because it was designed prior to the introduction of the Collections framework and does not implement the Map interface, which makes it difficult to use in conjunction with other parts of the framework.

In general, it’s recommended to use the Map interface or one of its implementations (such as HashMap or ConcurrentHashMap) instead of the Dictionary class.

Here’s an example of how to use the Dictionary class:

Java




import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Hashtable;
 
public class Main {
    public static void main(String[] args) {
        Dictionary<String, Integer> dictionary = new Hashtable<>();
 
        // Adding elements to the dictionary
        dictionary.put("A", 1);
        dictionary.put("B", 2);
        dictionary.put("C", 3);
 
        // Getting values from the dictionary
        int valueA = dictionary.get("A");
        System.out.println("Value of A: " + valueA);
 
        // Removing elements from the dictionary
        dictionary.remove("B");
 
        // Enumerating the elements of the dictionary
        Enumeration<String> keys = dictionary.keys();
        while (keys.hasMoreElements()) {
            String key = keys.nextElement();
            System.out.println("Key: " + key + ", Value: " + dictionary.get(key));
        }
    }
}


Output

Value of A: 1
Key: A, Value: 1
Key: C, Value: 3

Methods of util.Dictionary Class : 

1. put(K key, V value) : java.util.Dictionary.put(K key, V value) adds key-value pair to the dictionary.

Syntax :

public abstract V put(K key, V value)
Parameters : 
-> key
-> value
Return : 
key-value pair mapped in the dictionary

2. elements() : java.util.Dictionary.elements() returns value representation in dictionary.

Syntax :

public abstract Enumeration elements()
Parameters : 
--------
Return : 
value enumeration in dictionary

3. get(Object key) : java.util.Dictionary.get(Object key) returns the value that is mapped with the argumented key in the dictionary.

Syntax :

public abstract V get(Object key)
Parameters : 
key - key whose mapped value we want
Return : 
value mapped with the argumented key

4. isEmpty() : java.util.Dictionary.isEmpty() checks whether the dictionary is empty or not. 

Syntax :

public abstract boolean isEmpty()
Parameters : 
------
Return : 
true, if there is no key-value relation in the dictionary; else false

5. keys() : java.util.Dictionary.keys() returns key representation in dictionary.

Syntax :

public abstract Enumeration keys()
Parameters : 
--------
Return : 
key enumeration in dictionary

6. remove(Object key) : java.util.Dictionary.remove(Object key) removes the key-value pair mapped with the argumented key. 

Syntax :

public abstract V remove(Object key)
Parameters : 
key : key to be removed
Return : 
value mapped with the key

7. size() : java.util.Dictionary.size() returns the no. of key-value pairs in the Dictionary.

Syntax :

public abstract int size()
Parameters : 
-------
Return : 
returns the no. of key-value pairs in the Dictionary

Java




// Java Program explaining util.Dictionary class Methods
// put(), elements(), get(), isEmpty(), keys()
// remove(), size()
 
import java.util.*;
public class New_Class
{
    public static void main(String[] args)
    {
 
        // Initializing a Dictionary
        Dictionary geek = new Hashtable();
 
        // put() method
        geek.put("123", "Code");
        geek.put("456", "Program");
 
        // elements() method :
        for (Enumeration i = geek.elements(); i.hasMoreElements();)
        {
            System.out.println("Value in Dictionary : " + i.nextElement());
        }
 
        // get() method :
        System.out.println("\nValue at key = 6 : " + geek.get("6"));
        System.out.println("Value at key = 456 : " + geek.get("123"));
 
        // isEmpty() method :
        System.out.println("\nThere is no key-value pair : " + geek.isEmpty() + "\n");
 
        // keys() method :
        for (Enumeration k = geek.keys(); k.hasMoreElements();)
        {
            System.out.println("Keys in Dictionary : " + k.nextElement());
        }
 
        // remove() method :
        System.out.println("\nRemove : " + geek.remove("123"));
        System.out.println("Check the value of removed key : " + geek.get("123"));
 
        System.out.println("\nSize of Dictionary : " + geek.size());
 
    }
}


Output: 

Value in Dictionary : Code
Value in Dictionary : Program

Value at key = 6 : null
Value at key = 456 : Code

There is no key-value pair : false

Keys in Dictionary : 123
Keys in Dictionary : 456

Remove : Code
Check the value of removed key : null

Size of Dictionary : 1

Advantages of Dictionary class:

  1. Legacy Support: The Dictionary class was part of the original Java Collections framework and has been part of Java since the beginning. This means that if you have legacy code that uses Dictionary, you can still use it in your new code.
  2. Simple to use: The Dictionary class is simple to use and provides basic key-value data structure functionality, which can be useful for simple cases.

Disadvantages of Dictionary class:

  1. Obsolete: The Dictionary class is considered obsolete and its use is generally discouraged. This is because it was designed prior to the introduction of the Collections framework and does not implement the Map interface, which makes it difficult to use in conjunction with other parts of the framework.
  2. Limited functionality: The Dictionary class provides basic key-value data structure functionality, but does not provide the full range of functionality that is available in the Map interface and its implementations.
  3. Not type-safe: The Dictionary class uses the Object class to represent both keys and values, which can lead to type mismatches and runtime errors.

Reference books:

  1. “Java Collections” by Maurice Naftalin and Philip Wadler. This book provides a comprehensive overview of the Java Collections framework, including the Dictionary class.
  2. “Java in a Nutshell” by David Flanagan. This book provides a quick reference for the core features of Java, including the Dictionary class.
  3. “Java Generics and Collections” by Maurice Naftalin and Philip Wadler. This book provides a comprehensive guide to generics and collections in Java, including the Dictionary class.

 



Similar Reads

Java.util.TimeZone Class (Set-2) | Example On TimeZone Class
TimeZone class (the methods of this class was discussed in this article Java.util.TimeZone Class | Set 1) can be used in many cases like using TimeZone class we can get the time difference in term of hour and minute between two places.Problem : How we can get time difference of time in terms of hours and minutes between two places of Earth?Solution
5 min read
Java.util.GregorianCalendar Class in Java
Prerequisites : java.util.Locale, java.util.TimeZone, Calendar.get()GregorianCalendar is a concrete subclass(one which has implementation of all of its inherited members either from interface or abstract class) of a Calendar that implements the most widely used Gregorian Calendar with which we are familiar. java.util.GregorianCalendar vs java.util.
10 min read
Java.util.concurrent.RecursiveAction class in Java with Examples
RecursiveAction is an abstract class encapsulates a task that does not return a result. It is a subclass of ForkJoinTask, which is an abstract class representing a task that can be executed on a separate core in a multicore system. The RecursiveAction class is extended to create a task that has a void return type. The code that represents the compu
3 min read
Java.util.concurrent.Phaser class in Java with Examples
Phaser's primary purpose is to enable synchronization of threads that represent one or more phases of activity. It lets us define a synchronization object that waits until a specific phase has been completed. It then advances to the next phase until that phase concludes. It can also be used to synchronize a single phase, and in that regard, it acts
7 min read
Java.util.concurrent.RecursiveTask class in Java with Examples
RecursiveTask is an abstract class encapsulates a task that returns a result. It is a subclass of ForkJoinTask. The RecursiveTask class is extended to create a task that has a particular return type. The code that represents the computational portion of the task is kept within the compute() method of RecursiveTask. RecursiveTask class is mostly use
2 min read
Java.util.BitSet class in Java with Examples | Set 1
BitSet is a class defined in the java.util package. It creates an array of bits represented by boolean values. Constructors: BitSet class Constructors / \ BitSet() BitSet(int no_Of_Bits)BitSet() : A no-argument constructor to create an empty BitSet object. BitSet(int no_Of_Bits): A one-constructor with an integer argument to create an instance of t
2 min read
Java.util.BitSet class methods in Java with Examples | Set 2
Methods discussed in this post: BitSet class methods. / / | | \ \ set() xor() clone() clear() length() cardinality() We strongly recommend to refer below set 1 as a prerequisite of this. BitSet class in Java | Set 1 set() : java.util.BitSet.set() method is a sets the bit at the specified index to the specified value. Syntax:public void set(int bitp
4 min read
Java.util.zip.DeflaterInputStream class in Java
Implements an input stream filter for compressing data in the "deflate" compression format. Constructor and Description DeflaterInputStream(InputStream in) : Creates a new input stream with a default compressor and buffer size. DeflaterInputStream(InputStream in, Deflater defl) : Creates a new input stream with the specified compressor and a defaul
3 min read
Java.util.zip.InflaterOutputStream class in Java
This class implements an output stream filter for uncompressing data stored in the "deflate" compression format. Constructors InflaterOutputStream(OutputStream out) : Creates a new output stream with a default decompressor and buffer size. InflaterOutputStream(OutputStream out, Inflater infl) : Creates a new output stream with the specified decompr
3 min read
Java.util.zip.InflaterInputStream class in Java
This class implements a stream filter for uncompressing data in the "deflate" compression format. It is also used as the basis for other decompression filters, such as GZIPInputStream. Constructors InflaterInputStream(InputStream in) : Creates a new input stream with a default decompressor and buffer size. InflaterInputStream(InputStream in, Inflat
3 min read
Java.util.zip.ZipOutputStream class in Java
This class implements an output stream filter for writing files in the ZIP file format. Includes support for both compressed and uncompressed entries. Constructor : ZipOutputStream(OutputStream out) : Creates a new ZIP output stream. ZipOutputStream(OutputStream out, Charset charset) : Creates a new ZIP output stream. Methods: void close() : Closes
3 min read
Java.util.jar.JarEntry class in Java
This class is used to represent a JAR file entry. Constructors : JarEntry(JarEntry je) : Creates a new JarEntry with fields taken from the specified JarEntry object. JarEntry(String name) : Creates a new JarEntry for the specified JAR file entry name. JarEntry(ZipEntry ze) : Creates a new JarEntry with fields taken from the specified ZipEntry objec
2 min read
Java.util.zip.GZIPInputStream class in Java
This class implements a stream filter for reading compressed data in the GZIP file format. Constructors GZIPInputStream(InputStream in) : Creates a new input stream with a default buffer size. GZIPInputStream(InputStream in, int size) : Creates a new input stream with the specified buffer size. Methods : void close() : Closes this input stream and
2 min read
Java.util.zip.ZipEntry class in Java
This class is used to represent a ZIP file entry. Constructors ZipEntry(String name) : Creates a new zip entry with the specified name. ZipEntry(ZipEntry e) : Creates a new zip entry with fields taken from the specified zip entry. Methods: Object clone() : Returns a copy of this entry. Syntax :public Object clone() Overrides: clone in class Object
4 min read
Java.util.jar.JarInputStream class in Java
The JarInputStream class is used to read the contents of a JAR file from any input stream. It extends the class java.util.zip.ZipInputStream with support for reading an optional Manifest entry. The Manifest can be used to store meta-information about the JAR file and its entries. Constructors JarInputStream(InputStream in) : Creates a new JarInputS
3 min read
Java.util.zip.ZipInputStream class in Java
This class implements an input stream filter for reading files in the ZIP file format. Includes support for both compressed and uncompressed entries. Constructors: ZipInputStream(InputStream in) : Creates a new ZIP input stream. ZipInputStream(InputStream in, Charset charset) : Creates a new ZIP input stream Methods : int available() : Returns 0 af
3 min read
Java.util.PriorityQueue class in Java
It is a priority queue based on priority heap. Elements in this class are in natural order or depends on the Constructor we used at this the time of construction. It doesn't permit null pointers. It doesn't allow inserting a non-comparable object, if it relies on natural ordering. Constructors: PriorityQueue(): Creates a PriorityQueue with the defa
6 min read
Java.util.Locale Class in Java | Set 1
As the name suggests util.Locale Class is used to perform locale tasks and provides locale information for the user. Declaration : public final class Locale extends Object implements Cloneable, Serializable Constructors : Locale(String L): Creates Locale from the given language code.Locale(String L, String C): Creates Locale from the given language
4 min read
Java.util.Locale Class in Java | Set 2
Java.util.Locale Class in Java | Set 1 More methods: getDisplayVariant() : java.util.Locale.getDisplayVariant() displays variant of the Locale Syntax : public final String getDisplayVariant() Parameters : ---- Return : ----------- getDisplayVariant(Locale in) : java.util.Locale.Locale in(Locale in) returns the variant of "in" locale. Syntax : publi
3 min read
Java.util.Random class in Java
Random class is used to generate pseudo-random numbers in java. An instance of this class is thread-safe. The instance of this class is however cryptographically insecure. This class provides various method calls to generate different random data types such as float, double, int. Constructors: Random(): Creates a new random number generator Random(
4 min read
Java.util.TimerTask class in Java
TimerTask is an abstract class defined in java.util package. TimerTask class defines a task that can be scheduled to run for just once or for repeated number of time. In order to define a TimerTask object, this class needs to be implemented and the run method need to be overridden. The run method is implicitly invoked when a timer object schedules
3 min read
Java.util.Timer Class in Java
Timer class provides a method call that is used by a thread to schedule a task, such as running a block of code after some regular instant of time. Each task may be scheduled to run once or for a repeated number of executions. Each timer object is associated with a background thread that is responsible for the execution of all the tasks of a timer
6 min read
Java.util.ArrayDeque Class in Java | Set 1
java.util.ArrayDeque class describes an implementation of a resizable array structure which implements the Deque interface. Array deques has not immutable and can grow as necessary. They are not thread-safe and hence concurrent access by multiple threads is not supported unless explicitly synchronized. Null elements are invalid in this structure. M
5 min read
Java.util.ArrayDeque Class in Java | Set 2
Java.util.ArrayDeque Class in Java | Set 1 More Methods of util.ArrayDeque Class : 16. offer(Element e) : java.util.ArrayDeque.offer(Element e) : inserts element at the end of deque. Syntax : public boolean offer(Element e) Parameters : e - element to add Return : true, if element is added else; false 17. offerFirst(Element e) : java.util.ArrayDequ
5 min read
Java.util.Observable class in Java
java.util.Observable is used to create subclasses that other parts of the program can observe. When an object of such subclass undergoes a change, observing classes are notified. The update( ) method is called when an observer is notified of a change. Note: Observing class must implement the Observer interface, which defines the update( ) method. A
8 min read
Java.util.UUID class in Java
A class that represents an immutable universally unique identifier (UUID). A UUID represents a 128-bit value. There exist different variants of these global identifiers. The methods of this class are for manipulating the Leach-Salz variant, although the constructors allow the creation of any variant of UUID (described below). There are four differe
7 min read
Java.util.Objects class in Java
Java 7 has come up with a new class Objects that have 9 static utility methods for operating on objects. These utilities include null-safe methods for computing the hash code of an object, returning a string for an object, and comparing two objects. Using Objects class methods, one can smartly handle NullPointerException and can also show customize
7 min read
Java.util.TimeZone Class | Set 1
TimeZone class is used to represents a time zone offset, and also figures out daylight savings.What is a Time Zone and Time Offset?"Time Zone" is used to describe the current time for different areas of the world. It refers to one of the specific regions out of the 24 total regions in the world that are divided up by longitude. Within each one of t
7 min read
Java.util.concurrent.Exchanger class with Examples
Exchanger is the most interesting synchronization class of Java. It facilitates the exchange of elements between a pair of threads by creating a synchronization point. It simplifies the exchange of data between two threads. Its operation is simple: it simply waits until two separate threads call its exchange() method. When that occurs, it exchanges
3 min read
Java.util.IntSummaryStatistics class with Examples
The IntSummaryStatistics class is present in java.util package. It takes a collection of Integer objects and is useful in the circumstances when we are dealing with a stream of integers. It maintains a count of the number of integers it has processed, their sum and various other statistics. The class can also be used with Streams. It is useful in t
3 min read
Article Tags :
Practice Tags :