Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

dictionary
class
object
java

Java Dictionary

Educative Answers Team

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 Dictionary object class is implemented in java.utils.

svg viewer

There are some Dictionary implementations 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 Dictionary
		Hashtable<String, String> my_dict = new Hashtable<String, String>();

        // using elements() method
        for (Enumeration x = my_dict.elements(); x.hasMoreElements();) 
        { 
            System.out.println("Values in my_dict: " + x.nextElement());
        }

        // using isEmpty() method
        System.out.println("\nIs my dictionary empty?: " + my_dict.isEmpty() + "\n");

        // using keys() method
        for (Enumeration x = my_dict.keys(); x.hasMoreElements();) 
        { 
            System.out.println("Keys in my_dict: " + x.nextElement()); 
        }

		// using put method
		my_dict.put("01", "Apple");
		my_dict.put("10", "Banana");

		// using remove() method 
		// remove value at key 10
        my_dict.remove("10");
        System.out.println("Checking if the removed value exists: " + my_dict.get("10")); 
  
        // using get() method
        System.out.println("\nValue at key = 10: " + my_dict.get("10")); 
        System.out.println("Value at key = 11: " + my_dict.get("11"));

        // using size() method
        System.out.println("\nSize of my_dict : " + my_dict.size()); 
	}
} 

RELATED TAGS

dictionary
class
object
java
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring