how to create a HashTable using collections in java
Previous | Home | Next |
In this example we will see how to create a Hashtable.
For creating a Hashtable first of all we have to import the java.util package in which the java.util.Hashtable class is defined. In this example we have created a class named CollectionExample in which we have created a Hashtable and added some elements to it.
In a Hashtable the values are added using the key-value pair concept.The values are added corresponding to the key in a Hashtable and displayed by accessing the key in the Hashtable. In this example we have created a Hashtable by creating a default constructor of the Hashtable which is done as,
Hashtable<Integer,String> ht=new Hashtable<Integer,String>();
The above statment creates a Hashtable ht in which key is an integer type value and values are ot string types. This statements creates a anew, empty hashtable with a default initial capacity (11) and load factor, which is 0.75.
In this example we have created a class named CollectionExample. In this class we have created a Hashtable and elements are added to it using the put(Object key, Object value) method. The put method has the following syntax,
put(Object key, Object value)
This method maps the specifiedkey
to the specifiedvalue
in this hashtable.
Finally we have displayed the contents of the Hashtable.
package r4r.co.in;
import java.util.*;
public class CollectionExample {
/**
* @param args
*/
public static void main(String[] args) throws NullPointerException
{
// TODO Auto-generated method stub
try
{
Hashtable<Integer,String> ht=new Hashtable<Integer,String>();
ht.put(1, "r4r");
ht.put(2, "development");
ht.put(3, "tutorials");
ht.put(4, "shashi");
ht.put(5, "software developer");
System.out.println("The elements according to key are: ");
for(int i=1;i<=ht.size();i++)
{
System.out.println("key = "+i+","+"Value = "+ ht.get(i));
}
}
catch(NullPointerException e)
{
e.printStackTrace();
}
}
}
The output of the above example is the following one,
The elements according to key are:
key = 1,Value = r4r
key = 2,Value = development
key = 3,Value = tutorials
key = 4,Value = shashi
key = 5,Value = software developer
Previous | Home | Next |