Java Dictionary
A java dictionary is an abstract class that stores key-value pairs. Given a key, values can be stored and retrieved as needed; thus, a dictionary is a list of key-value pairs. Classes that implement this kind of interface include HashTables, HashMap, LinkedHashMap, etc.
The
Dictionaryobject class is implemented injava.utils.
There are some
Dictionaryimplementations that also allow various values to be referenced with a single key.
Class methods
-
Dictionary(): the default constructor. -
elements(): returns the enumeration of all the values in the dictionary. -
isEmpty(): checks whether or not the dictionary is empty. -
keys(): returns the enumeration of all the keys in the dictionary. -
put(K key, V value): adds the key-value pair to the dictionary. -
remove(K key): removes the key-value pair that was mapped with the specified key. -
get(K key): returns the value that was mapped to the specified key. -
size(): returns the number of key-value pairs in the Dictionary.
Code
The usage of the above methods is illustrated in the code snippet below:
import java.util.*;class My_Dictionary{public static void main(String[] args){// initializing My HashTable DictionaryHashtable<String, String> my_dict = new Hashtable<String, String>();// using elements() methodfor (Enumeration x = my_dict.elements(); x.hasMoreElements();){System.out.println("Values in my_dict: " + x.nextElement());}// using isEmpty() methodSystem.out.println("\nIs my dictionary empty?: " + my_dict.isEmpty() + "\n");// using keys() methodfor (Enumeration x = my_dict.keys(); x.hasMoreElements();){System.out.println("Keys in my_dict: " + x.nextElement());}// using put methodmy_dict.put("01", "Apple");my_dict.put("10", "Banana");// using remove() method// remove value at key 10my_dict.remove("10");System.out.println("Checking if the removed value exists: " + my_dict.get("10"));// using get() methodSystem.out.println("\nValue at key = 10: " + my_dict.get("10"));System.out.println("Value at key = 11: " + my_dict.get("11"));// using size() methodSystem.out.println("\nSize of my_dict : " + my_dict.size());}}
Free Resources