Introduction to Hashtable
20 November 2007Class 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.
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.
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); }
Related Posts:
Top Of Page | Trackback
If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.
It will look like this: Introduction to Hashtable
My gosh… So many incorrect things in this entry.
First of all, never use Hashtable, use Map. Hashtable is deprecated, slow, synchronized and only has one implementation.
Collisions don’t happen when the same key is used but when the hashed keys are equal.
When this happens, items are added anyway, not overwritten.
I’ll stop there, but please… stop writing tips until you’ve read some beginner Java material.