Java - Hashtable

java

// Hashtable

// Hashtable is a thread-safe version of HashMap.  HashMap is newer,
// and Hashtable was retrofit to implement the Map interface, but many people
// avoid using Hashtable because they consider it as legacy.  Use 
// ConcurrentHashMap if you need to support concurrency.

// To sort a Hashtable or HashMap by keys or values, we can use 
// Collections.list and Collections.sort, or we can use a TreeMap

Hashtable<String, String> hashtable = new Hashtable<String, String>();
hashtable.put("Key1","Chaitanya");

names = hashtable.keys();
while(names.hasMoreElements()) {
  key = (String) names.nextElement();
  System.out.println("Key: " +key+ " & Value: " +
  hashtable.get(key));
}

clear()
contains(value)
isEmpty()
keys()
put()
rehash()
remove()
size()
containsKey
containsValue
elements
get

How can we use Hashtable?

import java.util.Hashtable;
import java.util.Enumeration;

public class HashtableExample {

 public static void main(String[] args) {

   Enumeration names;
   String key;

   // Creating a Hashtable
   Hashtable<String, String> hashtable = new Hashtable<String, String>();

   // Adding Key and Value pairs to Hashtable
   hashtable.put("Key1","Chaitanya");
   hashtable.put("Key2","Ajeet");
   hashtable.put("Key3","Peter");
   hashtable.put("Key4","Ricky");
   hashtable.put("Key5","Mona");

   names = hashtable.keys();
   while(names.hasMoreElements()) {
      key = (String) names.nextElement();
      System.out.println("Key: " +key+ " & Value: " +
      hashtable.get(key));
   }
 }
}

The above example show us how to create a Hashtable object, and how to iterate over its key/value pairs.

What are the differences between Hashtable and HashMap?

Use ConcurrentHashMap if you need to support concurrency. Hashtable is considered legacy code (even though it was retrofitted). There's nothing about Hashtable that can't be done using HashMap or derivations of HashMap, so for new code, I don't see any justification for going back to Hashtable.

  1. Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.
  2. Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.
  3. One of HashMap's subclasses is LinkedHashMap, so in the event that you'd want predictable iteration order (which is insertion order by default), you could easily swap out the HashMap for a LinkedHashMap. This wouldn't be as easy if you were using Hashtable.

What methods are available with a Hashtable object?

Methods that exists for a Hashtable object:

  1. void clear(): Removes all the key-value mappings from Hashtable and makes it empty.
  2. Object clone(): Creates a shallow copy of this hashtable. All the structure of the hashtable itself is copied, but the keys and values are not cloned.
  3. boolean contains(Object value): Tests if some key maps into the specified value in this hashtable. This operation is more expensive than the containsKey method. This method is identical in functionality to containsValue.
  4. boolean isEmpty(): Tests if this hashtable maps no keys to values
  5. Enumeration keys(): Returns an enumeration of the keys contained in the hash table.
  6. Object put(Object key, Object value): Maps the specified key to the specified value in this hashtable.
  7. void rehash(): Increases the size of the hash table and rehashes all of its keys.
  8. Object remove(Object key): Removes the key (and its corresponding value) from this hashtable.
  9. int size(): Returns the number of key-value mappings present in Hashtable.
  10. String toString(): Returns the string equivalent of a hash table.
  11. boolean containsKey(Object key): Tests if the specified object is a key in this hashtable.
  12. boolean containsValue(Object value): Tests if the specified object is a value in this hashtable. Returns true if some value equal to value exists within the hash table. Returns false if the value isn’t found.
  13. Enumeration elements(): Returns an enumeration of the values contained in the hash table.
  14. Object get(Object key): Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

How can we remove all key/value pairs from a Hashtable object?

Use its .clear() method. The clear() method removes all the key-value mappings from Hashtable and makes it empty. Clears this hashtable so that it contains no keys.

How can we make a shadow copy of a Hashtable object?

Use the clone method. Creates a shallow copy of this hashtable. All the structure of the hashtable itself is copied, but the keys and values are not cloned. This is a relatively expensive operation.

What is the purpose of the contains() method of a Hashtable object?

boolean contains(Object value)

Tests if some key maps into the specified value in this hashtable. This operation is more expensive than the containsKey method.

How can we determine if a Hashtable object is empty?

Use its isEmpty() method.

How can we obtain an enumeration list of the keys contained in a Hashtable object?

Use its keys() method.

How can we iterate over the key/value pairs in a Hashtable object?

names = hashtable.keys();
while(names.hasMoreElements()) {
  key = (String) names.nextElement();
  System.out.println("Key: " +key+ " & Value: " +
  hashtable.get(key));
}

How can we put a new key/value pair into a Hashtable object?

Use its .put method:

Hashtable<String, String> hashtable = new Hashtable<String, String>();
hashtable.put("Key1","Chaitanya");

How can we increases the size of the hash table and rehashes all of its keys?

Use its rehash() method.

How can we remove a key/value pair from a Hashtable object?

Use its remove() method.

Object remove(Object key)

How can we determine the number of key/value pairs that exists inside a Hashtable object?

Use its size() method. The size method returns the number of key-value mappings present in Hashtable.

How can we obtain a String equivalent of a Hashtable object?

Use its toString() method.

How can we determine if a Hashtable object contains a particular key?

Use its containsKey() method.

How can we determine if a Hashtable object contains a particular value?

Use its containsValue() method.

How can we get a list of values that are in a Hashtable object?

Use its elements() method.

How can we get the value of a key/value pair that exists inside a Hashtable object?

Use its get() method. The get() method returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

How can we sort a Hastable object?

Hashtable doesn’t preserve the insertion order, neither it sorts the inserted data based on keys or values. Which means no matter what keys & values you insert into Hashtable, the result would not be in any particular order. If we need to sort a Hashtable object by its keys or values, we can use Collections.list and Collections.sort, however best thing to do is use LinkedHashMap or TreeMap.

How can we sort a Hashtable object by its key or value using the LinkedHashMap approach?

import java.util.*;
public class LinkedHashMapDemo
{
   public static void main(String args[])
   {
       LinkedHashMap<Integer, String> lhm= new LinkedHashMap<Integer, String>();
       lhm.put(10, "Chaitanya");
       lhm.put(1, "Ajeet");
       lhm.put(11, "Test");
       lhm.put(9, "Demo");
       lhm.put(3, "Anuj");

       // Get a set of the entries
       Set set = lhm.entrySet();

       // Get an iterator
       Iterator i = set.iterator();

       // Display elements
       while(i.hasNext()) {
         Map.Entry me = (Map.Entry)i.next();
         System.out.print(me.getKey() + ": ");
         System.out.println(me.getValue());
      }
   }
}

The above code gives us the result in the insertion order.

So, instead of using a Hashtable, we should use the LinkedHashMap.

How can we sort a Hashtable object by its key/value pairs using the TreeMap approach?

import java.util.*;
public class TreeMapDemo
{
   public static void main(String args[])
   {
      TreeMap<Integer, String> tm= new TreeMap<Integer, String>();
      tm.put(10, "Chaitanya");
      tm.put(1, "Ajeet");
      tm.put(11, "Test");
      tm.put(9, "Demo");
      tm.put(3, "Anuj");
      // Get a set of the entries
      Set set = tm.entrySet();
      // Get an iterator
      Iterator i = set.iterator();
      // Display elements
      while(i.hasNext()) {
        Map.Entry me = (Map.Entry)i.next();
        System.out.print(me.getKey() + ": ");
        System.out.println(me.getValue());
      }
  }
}

The above code sort the key/value pairs by its keys.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License