Java Dictionary Class with Example

Dictionary in Java is an abstract class that represents a key/value storage repository and operates as a map. If we have a key-value pair then we can store the value in the Dictionary object. Once the value is stored in a dictionary object, we can retrieve it by using its key. In Dictionary, any non-null object can be used as a key and as a value. 

Methods of Java Dictionary

The abstract methods defined by Java Dictionary are listed below:
1. Object put(Object key, Object value): This method is used to insert a key/value pair into a Dictionary.
2. Object get(Object key): It returns the object that contains the value associated with the key.
3. boolean isEmpty(): It checks whether the Dictionary is empty or not. If the Dictionary is empty it will return true else return false.
4. int size(): Returns the number of key/value pair in the dictionary.
5. Enumeration elements(): This method returns an enumeration of the values contained in the dictionary.
6. Enumeration keys(): This method returns an enumeration of the keys contained in the dictionary.


Java Dictionary Example:


import java.util.*;
class DictionaryExample{
 public static void main(String args[]){
  
  //creating a dictionary
  Dictionary dict = new Hashtable();
  
  //adding values in this dictionary
  dict.put(101, "Rahul");
  dict.put(109, "Amit");
  dict.put(103, "Vijay");
  dict.put(102, "Suresh");
  dict.put(108, "Prashant");
  
  //returns size of the dictionary
  System.out.println("Dictionary size is: "+dict.size());
  
  //enumeration of the values contained in the dictionary.
  for(Enumeration enm = dict.elements(); enm.hasMoreElements();){
   System.out.println("Dictionary values are: "+enm.nextElement());
  }
  
  //returns the value at key 108.
  System.out.println("Retrieve value at key 108: " +dict.get(108));
  
  //returns a boolean value
  System.out.println("Check dictionary is empty or not: " +dict.isEmpty());
  
  //enumeration of the keys contained in the dictionary.
  for(Enumeration enm = dict.keys(); enm.hasMoreElements();){
   System.out.println("Dictionary keys are: "+enm.nextElement());
  }
 }
}

Output:
Java Dictionary with Example


You may also enjoy these collections posts: 

TreeMap in Java with Example
How to use HashMap in Java with Example?
SortedMap interface in Java with Example
How to use ArrayDeque in Java?
How to add or remove elements in the Queue? 
Comparable vs Comparator interface in Java with Example 
TreeSet in Java with Example 
How to implement a stack data structure in Java? 
How to implement a LinkedList in Java?
How to remove a specified element from ArrayList?
 
Java Dictionary Class with Example Java Dictionary Class with Example Reviewed by Prashant Srivastava on March 26, 2019 Rating: 5

No comments:

Powered by Blogger.