Java Hashtable Tutorial
Summary: By the end of this "Java Hashtable Tutorial", you will understand the API methods.
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
- Hashtable is a legacy class introduced with JDK 1.0.
- Stores data in key/value pairs.
- 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).
- 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).
- Key and value cannot be null and if added, JVM throws NullPointerException. Infact, with null key, the code compiles but does not execute.
- Hashtable methods are synchronized (like Vector).
- Hashtable can be designed for generics to accept only one type of data.
- 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
- Hashtable(): Creates Hashtable object with an initial capacity of 11 elements and when exhausted increments by 0.75, known as load factor.
- Hashtable(int startCap): A Hashtable object is created with an initial capacity of startCap and when the capacity is exhausted, increments by 0.75.
- 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.
- 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
- int size(): Returns the number of elements (key/value pairs) stored.
- boolean isEmpty(): Checks for the existence of elements. If no elements exist, returns true else false.
- Set keys(): Returns a Set object containing all the keys.
- Enumeration elements(): Returns an Enumeration object containing all the values.
- boolean containsKey(Object k1): Checks for the existence of a key in the hashtable. Returns true if the key k1 exists else false.
- boolean contains(Object obj): Checks for the existence of a value in the hashtable. Returns true if the value obj exists else false.
- Object get(Object k1): Returns the value of the key k1.
- Object put(Object key, Object value): Adds a key/value pair to the hash table. Key and value are objects of any Java class.
- 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.
- 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.
- void clear(): Removes all the key/value pairs. After this method call, the size becomes zero.
- Object clone(): Clones the hash table object. Cloned object maintains encapsulation because the original object and cloned object maintains different memory locations.
- 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.
- 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.
- int hashCode(): Returns the hash code of the hash table.
Three programs are given on Hashtable
- Hashtable General: Uses the methods like elements, containsKey, put, get, contains and keys.
- 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.
- 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".