0 0
WP Ad Inserter plugin
Read Time:9 Second

The Java Hashtable class creates a hashtable by mapping keys to values. It implements the Map interface and inherits it from the Dictionary class.

Points to keep in mind

  • A Hashtable is a list’s array.
  • Every list is referred to as a bucket.
  • The hashcode() technique is used to determine the bucket’s position.
  • A Hashtable is a collection of values based on a key.
  • The Hashtable class in Java has distinct parts.
  • The Hashtable class in Java does not support null keys or values.
  • The Hashtable class in Java has been synchronized.
  • The capacity of the Hashtable class is 11 by default, whereas loadFactor is 0.75.

Declaration of the Hashtable class

Let’s have a look at the java.util.Hashtable class’s declaration.

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

Class parameters in a hashtable

Let’s look at the java.util.Hashtable class’s parameters.

  • This map’s kind of keys is designated by the letter K.
  • V: It refers to the mapped value type.

Hashtable’s Internal Workings

The key/value pairs are stored in a hashtable data structure array of buckets. The hashCode() method identifies which bucket the key/value combination is mapped to.

The hash function aids in the identification of a key’s location in the bucket list. Hashcode is a non-negative integer that is equal for equal Objects but may or may not be equal for unequal Objects in general. The hashtable uses the equals() method to determine whether two items are equal.

SUGGESTED READ

Two unequal Objects may have the same hashcode. Such a case is referred to as a collision. Further, a Hashtable employs an array of lists to resolve collisions. The pairings that map to a single bucket (array index) are stored in a list, and the array index contains a list reference.

Java Hashtable class constructors

Hashtable()

It builds an empty hashtable with the initial capacity and load factor set to default.

Hashtable(int capacity)

It takes an integer input and generates a hash table with a specific initial capacity.

Hashtable(int capacity, float loadFactor)

It’s used to construct a hash table with the initial capacity and loadFactor that you specify.

Hashtable(Map<? extends K,? extends V> t)

It builds a new hash table with the same mappings as the Map.

SUGGESTED READ

Java Hashtable class methods

void clear()

It’s used to clear the hash table’s contents.

Object clone()

It returns a Hashtable that is only a shallow replica of the original.

V compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)

It’s used to create a mapping between a key and its current mapped value (or null if there is no current mapping).

V computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction)

If the specified key is not already associated with a value (or is mapped to null), it is used to compute its value using the given mapping function and enters it into this map unless null.

V computeIfPresent(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)

If the value for the specified key is present and non-null, it is utilized to create a new mapping given the key and its existing mapped value.

SUGGESTED READ

Enumeration elements()

It gives you an enumeration of the hash table’s values.

Set<Map.Entry<K,V>> entrySet()

It gives you a set view of all the mappings on the map.

boolean equals(Object o)

It’s used to compare the supplied Object and the Map.

void forEach(BiConsumer<? super K,? super V> action)

It executes the specified action for each map entry until all entries are 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.

SUGGESTED READ

int hashCode()

It returns the Map’s hash code value.

Enumeration<K> keys()

It returns an enumeration of the hashtable’s keys.

Set<K> keySet()

It gives you a Set view of the keys on the map.

V merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction)

Associates the provided key with the non-null value if it is not already associated with a value or is null.

V put(K key, V value)

It adds the supplied value to the hash table with the specified key.

SUGGESTED READ

void putAll(Map<? extends K,? extends V> t))

It copies every key-value pair from the map to the hashtable.

V putIfAbsent(K key, V value)

If the specified key does not already have a value (or is mapped to null), it is associated with the given value and returns null; otherwise, it returns the current value.

boolean remove(Object key, Object value)

It clears the hashtable of the provided values and their related keys.

V replace(K key, V value)

It substitutes a specified key for the provided value.

boolean replace(K key, V oldValue, V newValue)

A given key replaces the previous value with the new one.

SUGGESTED READ

void replaceAll(BiFunction<? super K,? super V,? extends V> function)

Until all entries have been processed or the function throws an error, it replaces each entry’s value with the result of running the specified function on that entry.

String toString()

It returns a Hashtable object’s string representation.

Collection values()

It gives you a collection view of all 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)

If the value is equal to something in the hash table, this method returns true; otherwise, it returns false.

SUGGESTED READ

boolean containsKey(Object key)

If a key with the same name as the key exists in the hash table, this method returns true; otherwise, it returns false.

boolean isEmpty()

If the empty hash table, this method returns true; if it has at least one key, it returns false.

protected void rehash()

It’s used to expand the hash table’s size and rehash all its keys.

V get(Object key)

This method returns the object containing the key’s corresponding value.

V remove(Object key)

It’s utilized to get rid of the key and its value. The value linked with the key is returned by this method.

SUGGESTED READ

int size()

The number of entries in the hash table is returned by this method.

Using Hashtable to Perform Various Operations

Adding Elements

The put() method adds an element to the hashtable. On the other hand, the hashtable does not keep track of the insertion order. Internally, each element is generated with a different hash, and the elements are indexed based on this hash to improve efficiency.

// program for demonstrating how to add elements to a Hashtable in java import java.io.*;
import java.util.*; class CodeAddElementsToHashtable { public static void main(String args[]) { // it is needles mentioning the generic type twice Hashtable<Integer, String> namesHashtable = new Hashtable<>(); // using Generics to initialize a Hashtable Hashtable<Integer, String> languagesHashtable = new Hashtable<Integer, String>(); // Inserting the Elements using the put() method namesHashtable.put(1, "Green"); namesHashtable.put(2, "Mike"); namesHashtable.put(3, "Bright"); languagesHashtable.put(1, "Java"); languagesHashtable.put(2, "Python"); languagesHashtable.put(3, "Kotlin"); // Print the mappings to the console System.out.println("Mappings of namesHashtable : " + namesHashtable); System.out.println("Mappings of languagesHashtable : " + languagesHashtable); }
}

Changing Elements

If we want to change an element after it has been added, we can do it by using the put() method to add it again. Because the keys are used to index the elements in the hashtable, we can alter the value of the key by simply entering the updated value for the key we want to change.

// program demonstrating how to update a Hashtable import java.io.*;
import java.util.*;
class CodeUpdatesOnHashtable { public static void main(String args[]) { // Hashtable Initialization Hashtable<Integer, String> namesHashtable = new Hashtable<Integer, String>(); // Engaging the put method to insert new elements namesHashtable.put(1, "Green"); namesHashtable.put(2, "Mike"); namesHashtable.put(3, "Bright"); // print the initial map to the console System.out.println("The Original Hashtable is: " + namesHashtable); // Update the value at the second key namesHashtable.put(3, "Martin"); // print the updated map System.out.println("The Updated Hashtable is: " + namesHashtable); }
}

Remove Element

The remove() method removes an element from the Map. If a key is present on the map, this method takes the key value and removes the mapping for that key from the map.

// program for demonstrating the removal of mappings from the Hashtable import java.io.*;
import java.util.*;
class CodeRemovingMappingsFromHashtable { public static void main(String args[]) { // Initialization of a Hashtable Map<Integer, String> namesHashtable = new Hashtable<Integer, String>(); // Engaging the put method to insert new elements namesHashtable.put(1, "Green"); namesHashtable.put(2, "Mike"); namesHashtable.put(3, "Bright"); // Initial namesHashtable System.out.println("The original namesHashtable is: " + namesHashtable); // Remove the map entry with key 4 namesHashtable.remove(3); // the final namesHashtable System.out.println("The resultant updated namesHashtable : " + namesHashtable); }
}

Traversing a Hashtable

We can use an enhanced for loop to iterate the table. Iterating a hashtable is demonstrated below.

SUGGESTED READ

// program for illustrating the traversal of Hashtable in Java import java.util.Hashtable;
import java.util.Map; public class CodeIteratingHashtable { public static void main(String[] args) { // Create a Hashtable object. Hashtable<String, Integer> namesHashtable = new Hashtable<>(); // Using the put technique to add items namesHashtable.put("Green", 33); namesHashtable.put("Tyson", 16); namesHashtable.put("White", 67); // Using improved for loop iteration for (Map.Entry<String, Integer> e : namesHashtable.entrySet()) System.out.println(e.getKey() + " " + e.getValue()); }
}

Example: Java Hashtable

 import java.util.*; class CodeHashtable{ public static void main(String args[]){ Hashtable<Integer,String> stringHashtable=new Hashtable<Integer,String>(); stringHashtable.put(1,"Bright"); stringHashtable.put(2,"Joy"); stringHashtable.put(3,"Esther"); stringHashtable.put(4,"Arnold"); for(Map.Entry myEntry:stringHashtable .entrySet()){ System.out.println(myEntry.getKey()+" "+myEntry .getValue()); } } } 

Example: Java Hashtable’s remove() method

 import java.util.*; public class CodeHashtable { public static void main(String args[]) { Hashtable<Integer,String> nameHashtable=new Hashtable<Integer,String>(); nameHashtable.put(1,"Green"); nameHashtable.put(2,"Mike"); nameHashtable.put(3,"While"); nameHashtable.put(4,"Peter"); System.out.println("Hashtable before removal: "+ nameHashtable); // Remove value for key 4 nameHashtable.remove(4); System.out.println("Hashtable after removal: "+ nameHashtable); } } 

Example: Java’s Hashtable getOrDefault() method

 import java.util.*; class CodeHashtableGetOrDefault{ public static void main(String args[]){ Hashtable<Integer,String> nameHashtable=new Hashtable<Integer,String>(); nameHashtable.put(1,"Green"); nameHashtable.put(2,"Mike"); nameHashtable.put(3,"While"); nameHashtable.put(4,"Peter"); // As method arguments, we specify the if and else statements. System.out.println(nameHashtable .getOrDefault(2, "Not Found")); System.out.println(nameHashtable .getOrDefault(4, "Not Found")); } } 

Example: Java’s Hashtable putIfAbsent()

 import java.util.*; class Hashtable4{ public static void main(String args[]){ Hashtable<Integer,String> nameHashtable=new Hashtable<Integer,String>(); nameHashtable.put(1,"Green"); nameHashtable.put(2,"Mike"); nameHashtable.put(3,"While"); nameHashtable.put(4,"Peter"); System.out.println("Initial nameHashtable : "+nameHashtable); //Because the specified pair is unique, it inserts. nameHashtable.putIfAbsent(2,"James"); System.out.println("Updated nameHashtable: "+nameHashtable); //Because the specified pair already exists, this method returns the current value. nameHashtable.putIfAbsent(4,"Tyson"); System.out.println("Updated nameHashtable: "+nameHashtable); } } 

Example: Java’s Hashtable: Website

import java.util.*; class CodeWebsite { int id; String site_name,site_author,site_owner; int site_links; public CodeWebsite(int id, String site_ame, String site_author, String site_owner, int site_links) { this.id = id; this.site_name = site_name; this.site_author = site_author; this.site_owner = site_owner; this.site_links = site_links; } } public class CodeHashtable { public static void main(String[] args) { //Creating map of Books Map<Integer,CodeWebsite> siteHashtable=new Hashtable<Integer,CodeWebsite>(); //Creating Books CodeWebsite siteOne=new CodeWebsite(1,"codeunderscored.com","Brown","CodeUnderscored",200); CodeWebsite siteTwo=new CodeWebsite(2,"Google.com","James","Google Inc.",200000); CodeWebsite siteThree=new CodeWebsite(3,"Facebook","Wiley","Meta",100000); //Adding CodeWebsite to siteHashtable siteHashtable.put(1,siteOne); siteHashtable.put(2,siteTwo); siteHashtable.put(3,siteThree); //Traversing the siteHashtable for(Map.Entry<Integer, CodeWebsite> entry:siteHashtable .entrySet()){ int key=entry.getKey(); CodeWebsite new_site=entry.getValue(); System.out.println(key+" Details:"); System.out.println(new_site .id+" "+new_site .site_name+" "+new_site .site_author+" "+new_site .site_owner+" "+new_site .site_links); } } } 

Conclusion

A hash table is implemented using the Hashtable class, which maps keys to values. As a key or a value, any non-null object can be used. The objects used as keys must implement the hashCode and equals methods to store and retrieve objects from a hashtable successfully.

Source: https://www.codeunderscored.com/hashtable-in-java-explained-with-examples/

5 tricks every C# dev should know about LINQPad Previous post 5 tricks every C# dev should know about LINQPad
Logical Properties for Useful Shorthands Next post Logical Properties for Useful Shorthands

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.