Hashtable in java

Java Hashtable:

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

Note:

  • It is an array of a list.
  • Each list in the Java Hashtable class is known as a bucket.
  • The position of the bucket in the Java Hashtable class is identified by calling the hashcode() method.
  • It contains values based on the key.
  • It contains unique elements.
  • It does not allow the null key or value.
  • It is synchronized.
  • Its initial default capacity is 11.
  • Its load factor is 0.75.

Java Hashtable class declaration:

public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Cloneable, Serializable

Where:

  • K: The type of keys maintained by the Hashtable.
  • V: The type of mapped values.

Java Hashtable class Constructor:

Constructor Description
Hashtable() It will create an empty hashtable having the initial default capacity and load factor.
Hashtable(int capacity) It will create Hashtable and accept an integer parameter for initial capacity.
Hashtable(int capacity, float loadFactor) It will create a hash table having the specified initial capacity and loadFactor.
Hashtable(Map<? extends K,? extends V> t) It will create a new hash table with the same mappings as the given Map.

Java Hashtable class Methods:

Methods Description
void clear() It will remove or delete all the key-value pairs from the Hashtable.
boolean containsKey(Object key) It will return true if the Hashtable contains a value for the specified key.
boolean containsValue(Object value) It will return true if the Hashtable maps a value for the specified key.
Enumeration<V> elements() It will return the values in the Hashtable with the type Enumeration.
Object get(Object key) Returns the value to which the specified key is mapped, or null if the map contains no mapping for the key.
Set entrySet() It will return a Set that contains the key-value pairs of the map.
int hashCode() It will return the hash code value for the Hashtable
boolean isEmpty() It will return true if this Hashtable maps no key-value pairs otherwise return false.
Enumeration<K> keys() It will return the keys mapped in the Hashtable with the type Enumeration.
Set<K> keySet() It will return the keys mapped in the Hashtable as the type Set.
Value put(K key, V value) Maps the specified key with the specified value in the Hashtable.
void rehash() It will increase the size of the Hashtable and re-maps the key values according to the new size.
V replace(K key, V value) It will replace the value of the specified key with the value specified.
int size() It will return the number of key-value pairs on the map.
Value remove(Object key) It will remove or delete the key-value pair for the specified key from the map if it is present.
Collection values() It will return the collection of values present on the map.

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 w3spoint
 */
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

Java Hashtable Example: remove():

import java.util.*;  
public class HashtableExample{  
   public static void main(String args[]) {  
     Hashtable<Integer,String> hashtable=new Hashtable<Integer,String>();        
     hashtable.put(200,"A");    
     hashtable.put(202,"B");   
     hashtable.put(201,"C");    
     hashtable.put(203,"D");    
     System.out.println("Before remove: "+ hashtable);    
     // Remove value for key 202  
     hashtable.remove(202);  
     System.out.println("After remove: "+ hashtable);  
   }      
}

Output:

Before remove: {203=D, 202=B, 201=C, 200=A}
After remove: {203=D, 201=C, 200=A}

Java Hashtable Example: getOrDefault():

import java.util.*;  
class HashtableExample{  
 public static void main(String args[]){  
    Hashtable<Integer,String> hashtable=new Hashtable<Integer,String>();          
     hashtable.put(200,"A");    
     hashtable.put(202,"B");   
     hashtable.put(201,"C");    
     hashtable.put(203,"D");    
     //If and else statement as arguments of the method  
     System.out.println(hashtable.getOrDefault(201, "Not Exist"));  
     System.out.println(hashtable.getOrDefault(205, "Not Exist"));  
 }  
}

Output:

C
Not Exist

Java Hashtable Example: putIfAbsent():

import java.util.*;  
class HashtableExample{  
 public static void main(String args[]){  
     Hashtable<Integer,String> hashtable=new Hashtable<Integer,String>();          
     hashtable.put(200,"A");    
     hashtable.put(202,"B");   
     hashtable.put(201,"C");    
     hashtable.put(203,"D");    
     System.out.println("Initial Hashtable: "+hashtable);  
     //Inserts, as the specified key-value pair is not exist in Hashtable as of now
     hashtable.putIfAbsent(204,"E");  
     System.out.println("Updated Hashtable: "+hashtable);  
     //Returns the current value, as the specified key value pair already exist in Hashtable 
     hashtable.putIfAbsent(201,"C");  
     System.out.println("Updated Hashtable: "+hashtable);  
 }  
}

Output:

Initial Hashtable: {203=D, 202=B, 201=C, 200=A}
Updated Hashtable: {204=E, 203=D, 202=B, 201=C, 200=A}
Updated Hashtable: {204=E, 203=D, 202=B, 201=C, 200=A}

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

Please Share