Working With Dictionary Class in Java


In this article we are going to describe the Dictionary class in Java. The Dictionary class is the abstract parent of any class, such as Hashtable, that maps keys to values. Every key and every value is an object. In any one Dictionary object, every key is associated with at most one value. Given a Dictionary and a key, the associated element can be looked up. Any non-null object can be used as a key and as a value.

Method Details

1. size() : This method returns the number of entries in the dictionary; I mean this method returns a number of keys.


public abstract int size()

2. isEmpty : This method is used to check whether a dictionary is empty or not. In other words, if a dictionary has any elements then isEmpty returns true.


public abstract boolean isEmpty()

3. keys : This method returns an enumeration of the keys in this dictionary. The general contract for the keys method is that an Enumeration object is returned that will generate all the keys for which this dictionary contains entries.


public abstract Enumeration keys()

4. elements : This method returns list of elements in Enumeration form. The general contract for the isEmpty method is that if this dictionary contains an entry for the specified key, the associated value is returned; otherwise, null is returned.


 public abstract Object get(Object key)

Note: In the syntax the key - a key in this dictionary. null if the key is not mapped to any value in this dictionary. It will throw a null pointer exception.

5. put : This method is used to put the key and its value in the dictionary. If the dictionary already contains an entry for the specified key, then the value already in the dictionary for that key is returned, after modifying the entry to contain the new element. If this dictionary does not already have an entry for the specified key, an entry is created for the specified key and value, and null is returned.

Note: Neither the key nor the value can be null.


public abstract Object put(Object key,Object value)

6. remove This method is used to remove the particular key value. If your key does not exist in the dictionary then nothing happens. And it returns the mapped keys values.


 public abstract Object remove(Object key)


import java.util.*;

public class DictionaryDemo {

public static void main(String[] args)


Dictionary d=new Hashtable();


    d.put("1", "abhishek");

    d.put("2","rohtash" );

    d.put("3","abhishek" );

    d.put("4","sanjoli" );

    d.put("10","amit" );


    System.out.println(d.remove("10")+"  has been removed");

    System.out.println("the  value of key 10 = " +d.get("10"));


 for (Enumeration e = d.keys();e.hasMoreElements();)









Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now