Sponsored Links

Ad by Google
Hashtable is again an implementation of java.util.Map interface, In our previous post we have seen an example of HashMap implementation. In this post we are going to show you a very simple example of Hashtable

What is Hashtable

Hashtable is an implementation of java.util.Map interface and also extends Dictionary class. It is again works on Hashing principal and allows you to store the elements in the form of key and value pair. Hashtable is of course roughly equivalent to HashMap except that Hashtable is synchronized and does not allow null as a key or value. To store the element into the Hashtable uses put() method and to retrieve back the element from the Hashtable get() method is used. To make this put and get method works successfully, the key used inside the Hashtable must implement the hashCode() and equals() method of java.lang.Object class. See why String is best key for HashMap or Hashtable here
Of course key used in Hashtable or HashMap must be unique otherwise values will overridden against the same key as per normal java standards and you will get the last one only.

Hashtable can be created using one of the three constructor, for performance point of view always use the constructor with initial capacity and load factor. The initial capacity is basically number of buckets, the default initial capacity is 11. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased, default load factor is .75, below are the example of three different constructors.

Hashtable<String, String> htable = new Hashtable<>();
Hashtable<String, String> htable2 = new Hashtable<>(5);
Hashtable<String, String> htable3 = new Hashtable<>(500,.80f);

How to use Hashtable Example

package com.javamakeuse.poc;

import java.util.Hashtable;

public class HashTableExample {
 public static void main(String[] args) {
  Hashtable<String, Double> salehTable_2015 = new Hashtable<>();
  salehTable_2015.put("Jan", 30000d);
  salehTable_2015.put("Feb", 25000d);
  salehTable_2015.put("March", 31000d);

  for (String key : salehTable_2015.keySet()) {

   System.out.println("The sale of " + key + " is - "
     + salehTable_2015.get(key));

Hashtable is UN-order and UN-sorted that is why output is not in ordered. How to sort a HashMap or Hashtable here and see the differences between Hashtable and HashMap

The sale of March is - 31000.0
The sale of Jan is - 30000.0
The sale of Feb is - 25000.0

Sponsored Links


Post a Comment