How to create and use Hashtable?

This post explains implementation of Hashtable. We can find this class in java.util. Hashtable maps keys to values , these keys and values can be any non null objects. Hashtable uses hashing function algorithm so the object which we use for key must implement equals and hashcode methods.

Initial capacity and the load factor are the two things which controls or affects its performance. Capacity is the number of buckets in the Hashtable and Initial capacity is the capacity at the Hashtable object creation. Load factor is the limit to which it gets decided that capacity of Hashtable should be increased. This capacity increase after load factor reach is done by rehash method. Ideally 0.75 which is the default load factor offers great choice considering space and time costs.

Now lets see How to create a Hashtable?

Hashtable fruitsToColors = new Hashtable(); // Creating Hashtable instance
fruitsToColors.put("Watermelon", "red');
fruitsToColors.put("Mango", "Green")

In above example we are putting fruits as key and its colors as its value. Hashtable has a put method which takes keys and value as an argument.

Now lets see how we can retrieve the values from the Hashtable using key.

String fruitColor = ( String ) fruitsToColors.get( "Watermelon" );

Hashtable have get method, which takes key as an argument and return value in form of object for the specified key.

Few things are important to know about the Hashtable :

1. Hashtable is synchronized , it means the methods in the Hashtable are synchronized in other words thread safe.

2. Hashtable unlike HashMap doesnt allow any null value or key.

3. Hashtable is not ordered.

4. Hashtable is not sorted.
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment


Post a Comment