• September 3, 2014
  • Core Java
  • Comments Off on Hashtable in java

Hashtable in java

Hashtable:

Hashtable extends Dictionary class and implements Map interface. It contains elements in key-value pair. It not allowed duplicate key. It is synchronized. It can’t contain null key or value. It uses hashcode() method for finding the position of the elements.

Hashtable example:

HashtableTest.java

import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
 
/**
 * This class is used to show the Hashtable functionality.
 * @author javawithease
 */
public class HashtableTest {
	public static void main(String args[]){
		//Create Hashtable object.
		Hashtable hashtable = new Hashtable();
 
		//Add objects to the Hashtable.
		hashtable.put(2,"Bharat");
		hashtable.put(1,"Richi");
		hashtable.put(5,"Sahdev");
		hashtable.put(3,"Rajesh");
		hashtable.put(4,"Himanshu");
 
		//Print the Hashtable object.
		System.out.println("Hashtable elements:");
		System.out.println(hashtable);
 
		//Get iterator
		Set set=hashtable.entrySet();  
		Iterator iterator=set.iterator();  
 
		//Print the Hashtable elements using iterator.
		System.out.println("Hashtable elements using iterator:");
		while(iterator.hasNext()){
		   Map.Entry mapEntry=(Map.Entry)iterator.next();	
		   System.out.println("Key: " + mapEntry.getKey() + 
		       ", " + "Value: " + mapEntry.getValue());   
		}  
	}
}

Output:

Hashtable elements:
{5=Sahdev, 4=Himanshu, 3=Rajesh, 2=Bharat, 1=Richi}
Hashtable elements using iterator:
Key: 5, Value: Sahdev
Key: 4, Value: Himanshu
Key: 3, Value: Rajesh
Key: 2, Value: Bharat
Key: 1, Value: Richi

Download this example.
 
Next Topic: ListIterator interface in java with example.
Previous Topic: Properties class in java with example.

Related Topics:

Collection framework in java.
Collection interfaces in java.
Collection interface in java with example.
Set interface in java with example.
SortedSet interface in java with example.
List interface in java with example.
Map interface in java with example.
Daemon thread in java in java with example.
SortedMap interface in java with example.
Queue interface in java with example.
Deque interface in java with example.
Enumeration interface in java with example.
Collection classes in java with example.
HashSet in java with example.
LinkedHashSet in java with example.
TreeSet in java with example.
ArrayList in java with example.
LinkedList in java with example.
HashMap in java with example.
LinkedHashMap in java with example.
TreeMap in java with example.
PriorityQueue in java with example.
ArrayDeque in java with example.
Abstract classes in collection framework in java with example.
Sorting in java with example.
Comparable interface in java with example.
Comparator interface in java with example.
Properties class in java with example.
Hashtable in java with example.
ListIterator interface in java with example.

 


Comments are closed.