Java Hashtable Tutorial

Java Hashtable Tutorial

Summary: By the end of this "Java Hashtable Tutorial", you will understand the API methods.

class Hashtable

Elements in Stack and Vector are single entities. Hashtable is very different. It stores in pairs of words known as key/value pair. To store a value, a key is to be supplied. Using the key, the value can be retrieved from the data structure. Key works as an ID to search and get the value.

Properties of Hashtable
  1. Hashtable is a legacy class introduced with JDK 1.0.
  2. Stores data in key/value pairs.
  3. It does not accept duplicate keys. If the same key is added twice, the earlier one is replaced (overwritten), that is old value is lost (but is not an error).
  4. Value can be same for different keys (like value red can be there for keys tomato and apple or two students with roll number 40 and 50 may have the same birthday).
  5. Key and value cannot be null and if added, JVM throws NullPointerException. Infact, with null key, the code compiles but does not execute.
  6. Hashtable methods are synchronized (like Vector).
  7. Hashtable can be designed for generics to accept only one type of data.
  8. It is equivalent in collections framework is HashMap
Following is the class signature

public class Hashtable extends Dictionary implements Map, Cloneable, Serializable

Hashtable is from Dictionary. Dictionary is an abstract class. From JDK 1.2, Dictionary became obsolete (superseded, out-dated) in favor of Map. From JDK 1.2, Hashtable became a part of collections framework by implementing Map interface.

Following are the constructors
  1. Hashtable(): Creates Hashtable object with an initial capacity of 11 elements and when exhausted increments by 0.75, known as load factor.
  2. Hashtable(int startCap): A Hashtable object is created with an initial capacity of startCap and when the capacity is exhausted, increments by 0.75.
  3. Hashtable(int startCap, float lfact): A Hashtable object is created with an initial capacity of startCap and when the capacity is exhausted, increments by lfact, load factor. Negative values raise IllegalArgumentException.
  4. Hashtable(Map m1): A Hashtable object is created with default elements of map m1. Map elements are added to Hashtable. Like this, Hashtable and Map are interoperable. The initial capacity is just sufficient to store the elements of Map m1 and increments by the default load factor 0.75. If m1 does not contain elements, NullPointerException is thrown.
Hashtable Internal Mechanism

Hashtable includes two properties – capacity and load factor. Capacity is the storing capacity of the hash table and load factor is the incrementing factor used to increase the existing capacity when it is exhausted. The default capacity is 11 (like vector comes with 10) and default load factor is 0.75. The initial capacity and load factor can be customized by using above second and third constructors. When the current capacity is used out, the increment will be on the existing capacity like existingCapacity * 0.75. Like vector, a new location is searched for the new capacity and copies the elements of the old location into location. This is called as rehashing as rehash() method is called. Rehashing decreases the performance very considerably. To overcome this, the second overloaded constructor can be used where initial capacity required by the programmer can be given at the time of object creation itself.

Following are some important methods
  1. int size(): Returns the number of elements (key/value pairs) stored.
  2. boolean isEmpty(): Checks for the existence of elements. If no elements exist, returns true else false.
  3. Set keys(): Returns a Set object containing all the keys.
  4. Enumeration elements(): Returns an Enumeration object containing all the values.
  5. boolean containsKey(Object k1): Checks for the existence of a key in the hashtable. Returns true if the key k1 exists else false.
  6. boolean contains(Object obj): Checks for the existence of a value in the hashtable. Returns true if the value obj exists else false.
  7. Object get(Object k1): Returns the value of the key k1.
  8. Object put(Object key, Object value): Adds a key/value pair to the hash table. Key and value are objects of any Java class.
  9. Object remove(Object k1): Deletes the key/value pair of key k1. Returns the value of the key deleted. After this method call, size becomes one less.
  10. void putAll(Map m1): Places all the key/value pairs of Map m1 in the hash table. If the hash table is already having the same keys, their values are replaced.
  11. void clear(): Removes all the key/value pairs. After this method call, the size becomes zero.
  12. Object clone(): Clones the hash table object. Cloned object maintains encapsulation because the original object and cloned object maintains different memory locations.
  13. Set keySet(): Returns a Set object containing all the keys of Hashtable. One similarity is Hashtable and Set does not allow duplicates. Adding and removing elements in Set also reflects in Hashtable.
  14. Collection values(): Returns an object of Collection. The values in a hash table and Collection can have duplicates. For this reason, designers preferred to return Collection instead of Set.
  15. int hashCode(): Returns the hash code of the hash table.
Three programs are given on Hashtable
  1. Hashtable General: Uses the methods like elements, containsKey, put, get, contains and keys.
  2. Hashtable Generics: Creates generics Hashtable storing strings and integers and uses the methods like keySet, values, hashCode, putAll, clear, size, iterator, remove and isempty etc.
  3. Hashtable Special: Uses the methods like clone(), hashCode() and the values are printed in the ascending order of keys.

Pass your suggestions or comments to improve the quality of this tutorial "Java Hashtable Tutorial".

Leave a Comment

Your email address will not be published.