A generic class for constructing dictionaries (maps) in Java

The following is the specification of useful members of a Java (generic) map/dictionary/hashtable class HashMap useful in developing translators. A closely equivalent C# (generic) version appears lower on this page.

The earlier versions of Java and C# did not have generic versions of classes like these, but worked with elements of the Object class, which necessitated casting operations.

  import java.util.*;

  class HashMap<K,V>
  // Class for constructing a dictionary (map) of elements with keys of type and values of type V in C#

    public HashMap<K,V>()
    // Empty dictionary constructor

    public HashMap<K,V>(int capacity)
    // Empty dictionary with specified initial capacity

    public void clear()
    // Clears all elements from dictionary

    public int size()
    // Returns number of elements in dictionary

    public V put(K key, V value)
    // Adds (K, V) to dictionary (replacing any existing entry with that key)

    public V get(K key)
    // Retrieves an element with specified key from dictionary, or null if no such element exists

    public boolean isEmpty()
    // Returns true if dictionary is empty

    public boolean containsKey(K key)
    // Returns true if element with specified key is in the dictionary

    public boolean containsValue(V value)
    // Returns true if element with specified value is in the dictionary

    public remove(K key)
    // Removes the element with specified key from dictionary (no effect if no such element exists)

    public Set<K> keySet()
    // Returns a set of all the keys in the dictionary (useful for iterations)

    public Collection<V> values()
    // Returns a collection of all the values in the dictionary (useful for iterations)

    public Set<MapEntry<K, V>> entrySet()
    // Returns a set of all the key/value pairs in the dictionary (useful for iterations)

  } // HashMap
Here is a sample program showing the use of this library
   import library.*;
   import java.util.*;

   class ShowGenericDictionary {
   // Demonstrate simple application of the generic HashMap dictionary class in Java

     static class Entry {
       public String name;
       public int age;                                     // other fields could be added

       public Entry(String name, int age) {                // constructor
         this.name = name;
         this.age = age;
       }

       public String toString() {
         return name + " " + age;
       } // toString

     } // Entry

     static HashMap<String, Entry> dict = new HashMap<String, Entry>();  // global for simplicity here!

     public static void main (String[] args) {

       boolean found = false;
       Entry lookEntry = null;


       // Build a dictionary of students' IDs, names and ages
       IO.writeLine("Supply a list of student numbers, first names and ages.  CTRL-Z to terminate");
       do {
         String studentNumber = IO.readWord();
         if (IO.eof()) break;
         String name = IO.readWord();
         int age = IO.readInt();
         IO.readLn();
         dict.put(studentNumber, new Entry(name, age));       // add to dictionary (hash table)
       } while (!IO.eof());

       // Now demonstrate accesses to this dictionary

       Entry patEntry = new Entry("Pat", 61);                 // that fellow again!
       dict.put("63T0844", patEntry);                         // add him to the dictionary anyway

       IO.writeLine(dict.size() + " items stored");           // report size of dictionary

       IO.writeLine(dict.containsKey("Pat"));                 // false
       IO.writeLine(dict.containsKey("63T0844"));             // true
       IO.writeLine(dict.containsValue(patEntry));            // true

       dict.put("66A1234", new Entry("Peter", 69));           // not there so add("66A1234", "Peter", 69);
       IO.writeLine(dict.get("66A1234"));                     // just to make sure, use indexer to retrieve entry value

       patEntry.age = 69;                                     // Modify Pat's record (values are public, so you can)
       dict.put("66A1234", new Entry("Richard", 63));         // Replace the old entry completely
       IO.writeLine(dict.get("63T0844"));                     // Just to convince you
       IO.writeLine(dict.get("66A1234"));                     // Just to convince you

       found = dict.get("66A1234") != null;                   // get should succeed, so return true
       IO.writeLine("Peter " + found);                        // Peter  true
       found = dict.get("00F3434") != null;                   // get should fail gracefully, so return null
       IO.writeLine("Fred " + found);                         // Fred   false true
       IO.writeLine();

       Set<String> keys = dict.keySet();
       for (String s : keys) IO.writeLine(s);                 // iterate over keys
       IO.writeLine();

       for (String s : dict.keySet()) IO.writeLine(s);        // iterate over keys directly
       IO.writeLine();

       Collection<Entry> values = dict.values();
       for (Entry e : values) IO.writeLine(e);                // iterate over values
       IO.writeLine();

       for (Entry e : dict.values()) IO.writeLine(e);         // iterate over values directly
       IO.writeLine();

       dict.remove("63T0844");                                // Pat has had his turn - get rid of him

       for (Map.Entry<String, Entry> me : dict.entrySet())    // retrieve both key and value components
         IO.writeLine(me.getKey() + " : " + me.getValue());
       IO.writeLine();

       dict.remove("63T0844");                                // Pat has had his turn - and we already get rid of him
       dict.remove("60Z5674");                                // Zed was never there - ignore gracefully

     } // main

   } // ShowGenericDictionary


The following is the specification of useful members of the C# generic map/dictionary/hashtable Dictionary class useful in developing translators. A closely equivalent Java version appears earlier on this page.

The earlier versions of Java and C# did not have generic versions of such classes, but worked with elements of the Object class, which necessitated casting operations.

  using System.Collections.Generic;

  class Dictionary<K,V>
  // Class for constructing a dictionary (map) of elements with keys of type and values of type V in C#

    public Dictionary<K,V>()
    // Empty dictionary constructor

    public Dictionary<K,V>(int capacity)
    // Empty dictionary with specified initial capacity

    public void Clear()
    // Clears all elements from dictionary

    public int Count ( get; }
    // Returns number of elements in dictionary

    public void Add(K key, V value)
    // Adds (K, V) to dictionary (replacing any existing entry with that key)

    V this [K key]  { set; }
    // indexer - adds new element, or replaces existing element, using specified key

    V this [K key]  { get; }
    // indexer - retrieves element using specified key, or raises exception if not present
    // (Protect yourself by using ContainsKey or TryGetValue!)

    // public bool IsEmpty() - not a member

    public bool ContainsKey(K key)
    // Returns true if element with specified key is in the dictionary

    public bool ContainsValue(V value)
    // Returns true if element with specified value is in the dictionary

    public bool TryGetValue(K key, out V value)
    // Returns true if element with specified key is in the dictionary, returning that value
    // Returns false if element with specified key is  notin the dictionary, returning null

    public Remove(K key)
    // Removes the element with specified key from dictionary (no effect if no such element exists)

    public ICollection<K> Keys { get; }
    // Returns a set of all the keys in the dictionary (useful for iterations)

    public ICollection<V> Values ( get; }
    // Returns a collection of all the values in the dictionary (useful for iterations)

    // Iterating drectly over a generic dictionay interface returns a sequence of KeyValuePair
    // constructs
    //
    // public struct KeyValuePair <K, V> {
    //    public K Key   { get ; }
    //    public V Value { get ; }
    // } // KeyValuePair

  } // Dictionary
Here is a sample program like the one given earlier showing the use of this library
   using Library;
   using System.Collections.Generic;
   using System.Text;

   class ShowGenericDictionary {
   // Demonstrate simple application of the generic Dictionary class in C#

     class Entry {
       public string name;
       public int age;                                     // other fields could be added

       public Entry(string name, int age) {                // constructor
         this.name = name;
         this.age = age;
       }

       public override string ToString() {
         return name + " " + age;
       } // ToString

     } // Entry

     static Dictionary<string, Entry> dict = new Dictionary<string, Entry>();          // global for simplicity here!

     public static void Main (string[] args) {

       bool found = false;
       Entry lookEntry = null;

       // Build a dictionary of students' IDs, names and ages

       IO.WriteLine("Supply a list of student numbers, first names and ages.  CTRL-Z to terminate");
       do {
         string studentNumber = IO.ReadWord();
         if (IO.EOF()) break;
         string name = IO.ReadWord();
         int age = IO.ReadInt();
         IO.ReadLn();
         dict.Add(studentNumber, new Entry(name, age));       // add to end of list
       } while (!IO.EOF());

       // Now demonstrate accesses to this dictionary

       Entry patEntry = new Entry("Pat", 61);                 // that fellow again!
       dict.Add("63T0844", patEntry);                         // add him to the dictionary anyway

       IO.WriteLine(dict.Count + " items stored");            // report size of dictionary

       IO.WriteLine(dict.ContainsKey("Pat"));                 // false
       IO.WriteLine(dict.ContainsKey("63T0844"));             // true
       IO.WriteLine(dict.ContainsValue(patEntry));            // true

       dict["66A1234"] = new Entry("Peter", 69);              // not there so add("66A1234", "Peter", 69);
       IO.WriteLine(dict["66A1234"]);                         // just to make sure, use indexer to retrieve entry value

       patEntry.age = 69;                                     // Modify Pat's record (values are public, so you can)
       dict["66A1234"] = new Entry("Richard", 63);            // Replace the old entry completely
       IO.WriteLine(dict["63T0844"]);                         // Just to convince you
       IO.WriteLine(dict["66A1234"]);                         // Just to convince you

       found = dict.TryGetValue("66A1234", out lookEntry);    // should succeed returning a valid entry
       IO.WriteLine("Peter " + found + " |  " + (lookEntry == null));    // Peter  true  false
       found = dict.TryGetValue("00F3434", out lookEntry);    // should fail gracefully, returning null
       IO.WriteLine("Fred " + found + " |  " + (lookEntry == null));     // Fred   false true
       IO.WriteLine();

       ICollection<string> keys = dict.Keys;
       foreach (string s in keys) IO.WriteLine(s);            // iterate over keys
       IO.WriteLine();

       foreach (string s in dict.Keys) IO.WriteLine(s);       // iterate over keys directly
       IO.WriteLine();

       ICollection<Entry> values = dict.Values;
       foreach (Entry e in values) IO.WriteLine(e);           // iterate over values
       IO.WriteLine();

       foreach (Entry e in dict.Values) IO.WriteLine(e);      // iterate over values directly
       IO.WriteLine();

       dict.Remove("63T0844");                                // Pat has had his turn - get rid of him

       foreach (KeyValuePair<string, Entry> kv in dict)       // retrieve both key and value components
         IO.WriteLine(kv.Key + " : " + kv.Value);
       IO.WriteLine();

       dict.Remove("63T0844");                                // Pat has had his turn - and we already get rid of him
       dict.Remove("60Z5674");                                // Zed was never there - ignore gracefully

       //  lookEntry = dict["Not there"];                     // throws exception; rather protect with TryGetValue or ContainsKey

     } // Main

   } // ShowGenericDictionary

Revised: 2014/08/09