Java

Hashtable in Java

A hash table is for key/value pairs. Internally, the values are stored in an array. Each key is converted into an index of the array. This conversion is known as hashing. It is done by a hash function internally. In other words, the keys do not have to be stored. All that is the hash-table, in java and in other computer languages. This article explains two constructors of the Java hastable and its commonly used methods.

The following five lines show words and their meanings:

lull : to make somebody relaxed and calm
light : the energy from the sun
darkness: absence of light
dad : a less formal word for father
cook : a person whose job is cooking

Each word can be considered a key, and each meaning can be considered a value. This list of key/value pairs, will be used throughout this article. The hashtable class is in the java.util.* package, which has to be imported.

Article Content

Construction
public Hashtable()

This method constructs an empty hash table. The following program creates an empty hashtable, called dic (for dictionary), and then give it five key/value pairs.

    import java.util.*;
    public class TheClass {
        public static void main(String[] args) {
            Hashtable<String, String> dic = new Hashtable<String, String>();
            dic.put("lull", "to make somebody relaxed and calm"); dic.put("light", "the energy from the sun");
            dic.put("darkness", "absence of light"); dic.put("dad", "a less formal word for father");
            dic.put("cook", "a person whose job is cooking");
        }
    }

Note that the key type has to be indicated on the left and right-hand sides of the constructor statement. The type of value also has to be indicated on both sides. The Java Hashtable class has the put() method to put a key/value pair into the hash-table.

public Hashtable(Map<? extends K,? extends V> t)

This constructor method would create a hashtable from another hashtable. The name of the hashtable of the above code is dic. Another hashtable can be created from dic as follows:

            Hashtable<String, String> dic2 = new Hashtable<String, String>(dic);

The new hashtable is dic2. At the moment, it has all the elements (key/value pairs) of the dic hashtable.

Accessing Key/Value Pairs
public V put(K key, V value)

This method puts a key/value pair into the hashtable. It returns the previous value of the specified key of this hashtable, or null if the key did not have a value. The following code illustrates this:

            Hashtable<String, String> hshtbl = new Hashtable<String, String>();
            String oldvalue1 = hshtbl.put("blue", "having the color of the sea on a clear day");
            System.out.println(oldvalue1);
            String oldvalue2 = hshtbl.put("blue", "color of a clear sky on a clear day");
            System.out.println(oldvalue2);

The output is:

    null
    having the color of the sea on a clear day

public void putAll(Map<? extends K,? extends V> t)

This method puts another hashtable into the hashtable of interest. It returns void. Imagine that the above hashtable, dic is already in the program. Imagine that another hashtable, dic3, with the following content is also already in the program:

    {"blue"="color of a clear sky on a clear day",
    "vector"="a course taken by an aircraft"}

All the content of dic3 can be included in dic, with the following statement:

        dic.putAll(dic3);

public int size()

This method returns the number of keys for the hashtable. The following code illustrates this:

            Hashtable<String, String> dic = new Hashtable<String, String>();
            dic.put("lull", "to make somebody relaxed and calm"); dic.put("light", "the energy from the sun");
            dic.put("darkness", "absence of light"); dic.put("dad", "a less formal word for father");
            dic.put("cook", "a person whose job is cooking");

            int sz = dic.size();
            System.out.println(sz);

The output is 5.

public V get(Object key)

This method returns the value to which the specified key was hashed to, or null if the key was not hashed to any value (array index). The following code illustrates this:

            Hashtable<String, String> dic = new Hashtable<String, String>();
            dic.put("lull", "to make somebody relaxed and calm"); dic.put("light", "the energy from the sun");
            dic.put("darkness", "absence of light"); dic.put("dad", "a less formal word for father");
            dic.put("cook", "a person whose job is cooking");

            System.out.println(dic.get("lull"));
            System.out.println(dic.get("light"));
            System.out.println(dic.get("vector"));

The output is:

    to make somebody relaxed and calm
    the energy from the sun
    null

public V remove(Object key)

This method removes the key and its corresponding value, from the hashtable. It returns the value for the key, or null if the key was not present The following code illustrates this:

            Hashtable<String, String> dic = new Hashtable<String, String>();
            dic.put("lull", "to make somebody relaxed and calm"); dic.put("light", "the energy from the sun");
            dic.put("darkness", "absence of light"); dic.put("dad", "a less formal word for father");
            dic.put("cook", "a person whose job is cooking");

            String ret1 = dic.remove("darkness");
            String ret2 = dic.remove("darkness");

            System.out.println(ret1);
            System.out.println(ret2);

The output is:

    absence of light
    null

public boolean isEmpty()

Returns true if the hashtable has no key hashed to a value (array index); and false otherwise. The following code shows how to use this method:

            Hashtable<String, String> dic4 = new Hashtable<String, String>();
            boolean bl = dic4.isEmpty();
            System.out.println(bl);

The output is true.

public void clear()

This method clears all the key/value pairs in the hashtable. The size of the hashtable becomes zero. The following code shows its use:

            Hashtable<String, String> dic5 = new Hashtable<String, String>();
            dic5.put("blue", "color of a clear sky on a clear day");
            dic5.put("vector", "a course taken by an aircraft");

            dic5.clear();

            System.out.println(dic5.size());

The output is 0.

Returning List from Hashtable
public Enumeration<V> elements()

This method returns an enumeration of the values of the hashtable. The Enumeration class has its methods. The following code shows how to obtain an enumeration of values of the hashtable, and how to use the enumeration methods, to read the values:

            Hashtable<String, String> dic = new Hashtable<String, String>();
            dic.put("lull", "to make somebody relaxed and calm"); dic.put("light", "the energy from the sun");
            dic.put("darkness", "absence of light"); dic.put("dad", "a less formal word for father");
            dic.put("cook", "a person whose job is cooking");

            Enumeration<String> e = dic.elements();
            while (e.hasMoreElements() == true) {
                String str = e.nextElement();
                System.out.println(str);
            }

The output is:

    a person whose job is cooking
    a less formal word for father
    the energy from the sun
    absence of light
    to make somebody relaxed and calm

Notice that the output order is not the input order. This is how hashtable in Java works.

public Enumeration<K> keys()

This method returns an enumeration of the keys of the hashtable. The Enumeration class has its methods. The following code hows how to obtain an enumeration of keys of the hashtable, and how to use the enumeration methods to read the keys:

            Hashtable<String, String> dic = new Hashtable<String, String>();
            dic.put("lull", "to make somebody relaxed and calm"); dic.put("light", "the energy from the sun");
            dic.put("darkness", "absence of light"); dic.put("dad", "a less formal word for father");
            dic.put("cook", "a person whose job is cooking");

            Enumeration<String> e = dic.keys();
            while (e.hasMoreElements() == true) {
                String str = e.nextElement();
                System.out.println(str);

The output is:

    cook
    dad
    light
    darkness
    lull

Notice that the output order is not the input order. This is how hashtable in Java works. The key is actually hashed to an index (number) of an array, whose cell content is the value.

public Set<Map.Entry<K,V>> entrySet()

This method returns a set-view collection of key/value pairs, of the hashtable. The following code shows how to handle the return set, of key/value pairs, and how to print all the key/value pairs:

            Hashtable<String, String> dic = new Hashtable<String, String>();
            dic.put("lull", "to make somebody relaxed and calm"); dic.put("light", "the energy from the sun");
            dic.put("darkness", "absence of light"); dic.put("dad", "a less formal word for father");
            dic.put("cook", "a person whose job is cooking");

            Set<Map.Entry<String,String>> c = dic.entrySet();
            Iterator<Map.Entry<String,String>> iter = c.iterator();
            while (iter.hasNext() == true) {
                Map.Entry<String,String> kv = iter.next();
                System.out.println(kv.getKey() + ": " + kv.getValue());
            }

The output is:

    cook: a person whose job is cooking
    dad: a less formal word for father
    light: the energy from the sun
    darkness: absence of light
    lull: to make somebody relaxed and calm

Though the corresponding values for keys have been maintained, the output order is not the input order. This is how hashtable in Java works.

Converting the Set of Key/Value Pairs to String
public String toString()

This method converts all the key/value pairs of the hashtable, into one long string. It does not matter, if the types of keys or values were not strings. This is illustrated by the following code:

            Hashtable<String, Integer> ht = new Hashtable<String, Integer>();
            ht.put("ten", 10);
            ht.put("twenty", 20);
            ht.put("thirty", 30);

            String str = ht.toString();
            System.out.println(str);

The output is:

    {twenty=20, ten=10, thirty=30}

Conclusion

A hash-table is a map of key/value pairs. Internally, a key is actually hashed into the index of an array. The value of that index is the value of the key/value pair. The Hashtable is a class in the java.util.* package, which should be imported before its construction and other methods, can be used.

About the author

Chrysanthus Forcha

Discoverer of mathematics Integration from First Principles and related series. Master’s Degree in Technical Education, specializing in Electronics and Computer Software. BSc Electronics. I also have knowledge and experience at the Master’s level in Computing and Telecommunications. Out of 20,000 writers, I was the 37th best writer at devarticles.com. I have been working in these fields for more than 10 years.