View RSS Feed

My Java Tips

Introduction to Hashtable

Rate this Entry
by , 11-09-2011 at 05:46 PM (1084 Views)
Class Hashtable is found in java.util package and is very useful data structure. If used sensibly, it can save time and can produce results efficiently. Hashtable class implements Cloneable, Map and Serializable interfaces.


Hashtable can be simply a table in the memory. Each value stored as a key associated to it. Values are retrieved also using keys so searching is very fast.. It is always a good idea to declare Hashtable of size much greater than what you need for faster processing/lookups.
Many experienced coders are of the opinion that one should have a Hashtable with 25% more capacity than needed and a load factor of 0.75 to control automatic growth of the lookup table when it gets too full.

Collisions are also possible in Hashtables. Collision means that you try to put 2 values with same key. In such case, the values are overwritten. To keep all the values, one can create Vector or ArrayList and then store to Hashtable with a key. A way to avoid collision is to use some function for key generation. Usually prime numbers are used as keys.
Now lets do it.

Java Code:
Hashtable hash = new Hashtable(10);

hash.put("CR", "Cricket");
hash.put("FO", "Football");
hash.put("BB", "Baseball");
hash.put("SW", "Swimming");
hash.put("BO", "Boxing");

// enumerate all the sports of the hashtable
Enumeration keys = hash.keys();
while ( keys.hasMoreElements() )
	{
		key = (String)keys.nextElement();
		sportsName = (String)hash.get( key );
		System.out.println( key + "-" + sportsName );
	}
Output:


FO-Football
CR-Cricket
BO-Boxing
BB-Bseball
SW-Swimming

To avoid collision, I created a simple method that takes Hashtable. Key and value as input. It then checks if the key is occupied or not. If now, the value is assigned to the key in the Hashtable.

Java Code:
public static void putInHashTable(Hashtable hash, String key,String value){
	if(hash.containsKey(key))
	   System.out.println("Key already exists in the Hashtable.");
	else
	   hash.put(key, value);
}

Submit "Introduction to Hashtable" to Facebook Submit "Introduction to Hashtable" to Digg Submit "Introduction to Hashtable" to del.icio.us Submit "Introduction to Hashtable" to StumbleUpon Submit "Introduction to Hashtable" to Google

Tags: None Add / Edit Tags
Categories
Java SE

Comments