coderz.py

Keep Coding Keep Cheering!

Hashtable class in Java Collection Framework

java thread class

The Hashtable class creates a hash table by mapping keys to values. As a key or value, any non-null object can be used. The objects used as keys must implement the hashCode and equals methods in order to successfully store and retrieve objects from a hashtable.

Hashtable class Declaration:
public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Cloneable, Serializable
Remember the following:
  • A Hashtable is an array of a list. Each list is referred to as a bucket. The bucket’s position is determined by using the hashcode() technique. A Hashtable is a collection of values based on the key.
  • The Java Hashtable class comprises distinct elements.
  • The Java Hashtable class does not support null keys or values.
  • The Hashtable class in Java is synchronized.
  • The default capacity of the Hashtable class is 11, and the loadFactor is 0.75.
Hashtable Constructors:

1)Hashtable(): It generates an empty hashtable with the default capacity and load factor.

Hashtable<K, V> ht = new Hashtable<K, V>();

2)Hashtable(int capacity): It takes an integer parameter and generates a hash table with a specified initial capacity.

Hashtable<K, V> ht = new Hashtable<K, V>(int initialCapacity);

3)Hashtable(int capacity, float loadFactor): It’s used to generate a hash table with the given starting capacity and loadFactor.

Hashtable<K, V> ht = new Hashtable<K, V>(int size, float fillRatio);

4)Hashtable(Map<? extends K,? extends V> t): It generates a new hash table with the same mappings as the supplied Map.

Hashtable<K, V> ht = new Hashtable<K, V>(Map m);
Hashtable Methods:
MethodDescription
void clear()It empties the hash table.
Object clone()It returns a shallow copy of the Hashtable.
V compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)It generates a mapping between the supplied key and its current mapped value.
V computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction)It computes its value using the mapping function provided.
Enumeration elements()It returns an enumeration of the hash table values.
Set<Map.Entry<K,V>> entrySet()It returns a set view of all the mappings in the map.
boolean equals(Object o)It compares the specified Object with the Map.
void forEach(BiConsumer<? super K,? super V> action)It executes the specified action for each map entry until all entries have been processed or the action throws an exception.
V getOrDefault(Object key, V defaultValue)It returns the value to which the supplied key is mapped, or defaultValue if no mapping for the key exists in the map.
int hashCode()It returns the hash code value for the Map
Enumeration<K> keys()It returns an enumeration of the keys in the hashtable.
Set<K> keySet()It returns a Set view of the keys contained in the map.
V merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction)Assign the provided key to the given non-null value if it is not already associated with a value or is associated with null.
V put(K key, V value)It adds the supplied value to the hash table with the specified key.
void putAll(Map<? extends K,? extends V> t))It is used to copy all the key-value pairs from the map to hashtable.
V putIfAbsent(K key, V value)If the specified key does not already have a value associated with it (or is mapped to null), it associates it with the given value and returns null; otherwise, it returns the current value.
boolean remove(Object key, Object value)It deletes the provided values and their related keys from the hashtable.
V replace(K key, V value)It substitutes the provided value for the specified key.
String toString()It returns the Hashtable object as a string representation.
Collection values()It gives you a collection view of the values on the map.
boolean contains(Object value)If a value equal to the value exists in the hash table, this method returns true; otherwise, it returns false.
boolean containsValue(Object value)This method returns true if some value is equal to the value that exists within the hash table, else returns false.
boolean containsKey(Object key)This method returns true if some key equal to the key exists within the hash table, else returns false.
boolean isEmpty()If the hash table is empty, this method returns true; otherwise, it returns false.
protected void rehash()It is used to expand the hash table and rehash all of its keys.
V get(Object key)This method returns the object that contains the value associated with the key.
V remove(Object key)It’s used to get rid of the key and its value. The value linked with the key is returned by this method.
int size()This method returns the number of hash table entries.
Example: Adding Elements

import java.io.*;
import java.util.*;

class Coderz {
	public static void main(String args[])
	{
		// No need to mention the
		// Generic type twice
		Hashtable<Integer, String> htobj = new Hashtable<>();


		// Inserting the Elements
		// using put() method
		htobj.put(1, "Coderzpy");
		htobj.put(2, "For");
		htobj.put(3, "2023");

		// Print mappings to the console
		System.out.println("Mappings of htobj : " + htobj);
	
	}
}
Output:
Mappings of htobj : {3=2023, 2=For, 1=Coderzpy}
Example: Changing Elements

import java.io.*;
import java.util.*;

class Coderz {
	public static void main(String args[])
	{
		// No need to mention the
		// Generic type twice
		Hashtable<Integer, String> htobj = new Hashtable<>();


		// Inserting the Elements
		// using put() method
		htobj.put(1, "Coderzpy");
		htobj.put(2, "For");
		htobj.put(3, "2023");

	  // print initial map to the console
        System.out.println("Initial Map " + htobj);
          
          // Update the value at key 2
        htobj.put(2, "coding");
          
          // print the updated map
        System.out.println("Updated Map " + htobj);
	
	}
}
Output:
Initial Map {3=2023, 2=For, 1=Coderzpy}
Updated Map {3=2023, 2=coding, 1=Coderzpy}
Example: Removing Element

import java.io.*;
import java.util.*;

class Coderz {
	public static void main(String args[])
	{
		// No need to mention the
		// Generic type twice
		Hashtable<Integer, String> htobj = new Hashtable<>();


		// Inserting the Elements
		// using put() method
		htobj.put(1, "Coderzpy");
		htobj.put(2, "For");
		htobj.put(3, "2023");

	  // print initial map to the console
        System.out.println("Initial Map " + htobj);
          
          // Update the value at key 2
        htobj.remove(2);
          
          // print the updated map
        System.out.println("Updated Map " + htobj);
	
	}
}
Output:
Initial Map {3=2023, 2=For, 1=Coderzpy}
Updated Map {3=2023, 1=Coderzpy}
Example:  Traversal of a Hashtable

import java.io.*;
import java.util.*;

class Coderz {
	public static void main(String args[])
	{
		// No need to mention the
		// Generic type twice
		Hashtable<Integer, String> htobj = new Hashtable<Integer, String>();


		// Inserting the Elements
		// using put() method
		htobj.put(1, "Coderzpy");
		htobj.put(2, "For");
		htobj.put(3, "2023");

	  for (Map.Entry<Integer, String> e : htobj.entrySet())
            System.out.println(e.getKey() + " "
                               + e.getValue());
	
	}
}
Output:
3 2023
2 For
1 Coderzpy

Note: also read about the Treemap class in Java Collection Framework

Follow Me

If you like my post, please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Leave a Comment

Your email address will not be published. Required fields are marked *

Advertisement