Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

What is Hashtable in Java? Explained with Examples

Updated on 03 July, 2023

7.51K+ views
17 min read

What is Hashtable in Java?

Hashtable in java maps the keys to values. The Hashtable inherits the Dictionary class and implements the map interface. Any non-null object can be used as a value or a key. The objects used as keys in Hashtable must implement the “hashcode” method and the “equals” method.  It was a part of “original java.util” but got the power to implement the map interface in Java 2.

Hashtable is integrated into collections framework in java and is similar to HashMap except that Hashtable is synchronized. 

Hashtable in Java Features 

A hashtable in Java is a part of the Java collections framework and implements the Map interface. It is backwards compatible because it derives from the completely worthless and dated Dictionary class. After understanding hashmap and hashtable in Java, let’s look at some of its salient characteristics: 

  • Key-Based Hashtables: As opposed to arrays, a hashtable in Java only requires a key to find the value, which could be a different object. 
  • Dynamic Capacity: The hashmap and hashtable in Java are capable of holding greater numbers of elements than the internal array can manage by using chaining and linked lists. 
  • Performance: The Java hashtables performance may be O(n) in the worst-case scenario when you must traverse a linked list to find the correct value object due to collision, irrespective of knowing that hashtables are made for quick searches or O(1) searches (constant time search operations). 

Note: Since worst-case performance is now capped at O(logN), and JDK uses binary trees as opposed to linked lists from Java 8, performance has been significantly enhanced.

  • Application: Maps or pairs of key-value items are stored in hashtables. As a result, it might be used to store client information, library books, or other documents. 
  • Sorting: A hashtable can’t be sorted. However, data that is sorted can be obtained and extracted by classifying the hash table’s list of keys and then extracting values via a LinkedHashMap or TreeMap to retrieve the values in the proper order. 
  • Collision: Collisions can happen in hashtables because distinct data items may collide and be related to the same bucket. That’s because their hash values clash. Different collision avoidance strategies, such as open addressing or chaining, can be used to tackle this. 
  • Synchronization: The hashtable class is thread-safe because it is synchronized. More than one thread can’t get to the Hashtable class instance at once. Because of this, its operations are slower than Java’s HashMaps. 

Note: Using HashMap rather than Hashtable in Java is advised if a thread-safe implementation isn’t necessary. 

Java Hashtable Example

import java.util.*;  
class Hashtable1{  
 public static void main(String args[]){  
  Hashtable<Integer,String> hm=new Hashtable<Integer,String>();

 

  hm.put(200,"Rohan");  
  hm.put(202,"Rohit");  
  hm.put(201,"Raunak");  
  hm.put(203,"Ramesh");

 

  for(Map.Entry m:hm.entrySet()){  
   System.out.println(m.getKey()+" "+m.getValue());  
  }  
 }  
}  

Output:

203 Ramesh
202 Raunak
201 Rohit
200 Rohan

Here is another Java hashtable example for the remove() operation: 

import java.util.*;  
public class Hashtable2 {  
   public static void main(String args[]) {  
  Hashtable<Integer,String> map=new Hashtable<Integer,String>();        
     map.put(200,"Rohan");    
     map.put(202,"Raunak");   
     map.put(201,"Rohit");    
     map.put(203,"Ramesh");    
     System.out.println("Before remove: "+ map);    
       // Remove value for key 202  
       map.remove(202);  
       System.out.println("After remove: "+ map);  
   }      
}

Output:

Before remove: {203=Ramesh, 202=Raunak, 201=Rohit, 200=Rohan}
After remove: {203=Ramesh, 201=Rohit, 200=Rohan}

With these two Java hashtable examples as well as the understanding of hashtable’s salient features, you should now have a solid grasp of this Java concept. 

Check out our free technology courses to get an edge over the competition.

Hierarchy of Hashtable in Java

Source:

The direct subclasses of Hashtable in java are Properties and UIDefaults.

  • Hashtable in java implements Serializable and Cloneable.
  • Hashtable in java extends Dictionary<K,V>.

Class Declaration- Hashtable in Java

The declaration for java.util.Hashtable class is:

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

Class Parameters- Hashtable in Java 

The parameters for java.util.Hashtable class are:

  • K: It stands for the different key types maintained by this map.
  • V: It stands for mapped value types.

Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs or Masters Programs to fast-track your career.

Working of Hashtable in Java

Hashtable is a data structure that stores keys or value pairs and is an array of buckets. The determination of the mapping of a bucket of keys or value pairs is achieved using the hashCode() method. 

This hashcode is a non-negative integer that is equal for equal objects. This may or may not be equal for unequal objects. The Hashtable in Java uses the equals() method to check whether two objects are equal or not.

Thus, the hash function determines the location for a given key in the bucket list. In simple words, an object is used as a key, and value is linked to the key. The hashing of key results in a hashcode. This hashcode represents the index at which values are stored in the Hashtable.

What is Collision in Hashtable in Java?

When two unequal objects have the same hashcodes in Hashtable, the condition is termed as collision. An array of lists is used to resolve collision in Hashtable. It is resolved by storing the pairs mapped to a single bucket in a list. This list reference is then stored in the array index.

In case of hash collision, the multiple entries in a single bucket must be searched sequentially.

What are the Parameters affecting the Performance of Hashtable in Java?

The main parameters that affect the performance of any instance of Hashtable are:

  • Initial Capacity:

The number of buckets in a Hashtable is called its capacity. The capacity of the Hashtable at the time of its creation is its initial capacity. It controls a tradeoff between wasted space and rehashes operations’ requirements. Thus setting high values of initial capacity wastes space in Hashtable. If the initial capacity is greater than the maximum number of entries, no rehash operations are possible.

  • Load Factor:

The measure of how full the Hashtable is allowed before its capacity is automatically increased is termed as the load factor of Hashtable in java. The default load factor value is 0.75, and it allows a good tradeoff between time and space costs. With an increase in load factor, the time cost to lookup an entry is increased, and space overhead decreases.

Constructors- Hashtable in Java

We need to import Hashtable in java from java.util.Hashtable. The different ways in which Hashtable can be created in java are:

  • Hashtable():

It creates an empty Hashtable with an initial capacity of 11 and the default load factor of 0.75. It can be explained using the following example.

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

Input:

Source: 

Output:

Source: 

  • Hashtable(int initialCapacity):

It creates a Hashtable with a default load factor of 0.75. The initial capacity is defined by the initialCapacity. It can be explained using the following example.

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

Input:

Source: 

Output:

Source: 

  • Hashtable(int size, float fillRatio):

It creates a Hashtable whose fill ratio is defined by fillRatio. It defines that how full a Hashtable can be before it is resized upwardly. The initial size in this constructor is specified by “size.” It can be explained using the following example.

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

Input:

Source: 

Output:

Source: 

  • Hashtable(Map<? Extends K,? extends V>m)

It creates a Hashtable that is initialized with the elements of “m.” It can be explained using the following example.

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

Input:

Output:

Source: 

Different Methods of Hashtable in Java

The different methods in the Java Hashtable class and their description are as below:

  • void clear() Method:

This method is used to reset the Hashtable.

  • Enumeration elements() Method:

An enumeration of the values in the Hashtable is returned by this method.

  • Object clone() Method:

This method returns a shallow copy of the Hashtable.

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

To return a set view of the mappings contained in the map, this method is used.

  • boolean equals(Object o) Method:

This method is used to compare the specified object within the hashmap of the table.

  •  int hashCode() Method:

This method returns the hash code value for the map.

  • Set<K> keySet() Method:

This method returns a Set view of the keys present in the map.

  • V put(K key, V value) Method:

This method inserts the defined value with the defined key in the Hashtable.

  • boolean remove(Object key, Object value) Method:

This method removes the specified values with the associated specified keys from the Hashtable.

  • V replace(K key, V value) Method:

This method replaces the defined value for a defined key.

  • String toString()Method:

This method returns the representation of the objects in Hashtable.

  • Collection values() Method:

This method returns a collection view of the values present in the map.

  • boolean contains(Object value) Method:

It returns to true if there is some value equal to the value that exists from the Hashtable. It otherwise returns false.

  • boolean containsValue(Object value) Method:

It returns true if there is some value equal to the value that exists from the Hashtable. It otherwise returns false.

  • boolean containsKey(Object key) Method:

It returns true if some key equal to the key exists in the Hashtable. It otherwise returns false.

  • boolean isEmpty() Method:

It returns true if the Hashtable is empty. It otherwise returns to false if it contains at least one key.

  • protected void rehash() Method:

This method is used to increase the size of the Hashtable and rehashes all of its keys.

  • V get(Object key) Method:

It returns the object that contains the value attached with the key.

  • V remove(Object key) Method:

This method is used to remove the key and its value. This method returns the value defined with the key.

  • int size() Method:

It returns to the number of entries present in the Hashtable.

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

This method computes the mapping for any specified key. It also computes its current mapped value and goes to null if there is no current mapping.

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

This method computes its value using the given mapping function if the specified key is not already associated with a value or to the condition in which it is mapped to null). It also enters it into this map unless it achieves null.

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

It further computes its current mapped value if the value for the specified key is present and is non-empty, along with its new mapping.

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

This method performs the given action for each entry in the map until all entries are done.

  • V getOrDefault(Object key, V defaultValue) Method:

This method returns to the value to which the defined key is mapped. It also returns to defaultValue if the map contains no mapping for the key.

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

This method associates a defined key with the given non-null value if it is not already associated with a value or is associated with null.

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

This method replaces the old value with the new value for the specified key.

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

This method copies all the key-value pair from the map to the Hashtable.

  • V putIfAbsent(K key, V value) Method:

This method associates the specified key with the given value. It returns null if it is already associated with a value (or is mapped to null), else it returns the current value.

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

It replaces the entry’s value with the result of introducing the given function on that entry only. It is done until all entries processor until the condition in which the function throws an exception.

Different Operations on Hashtable in Java

The different operations on Hashtable can be performed in the following ways:

  • Adding Elements:

The put() method is used to add an element to the Hashtable. Internally, a separate hash is generated for each element. The elements are indexed based on this hash only to make it more efficient. The insertion order is not retained in the Hashtable. For example:

Input:

Source: 

Output:

Source: 

  • Changing Elements:

If you want to change an element after adding, it can be done by again the element by using put(). The elements in a Hashtable are indexed using the keys. Thus, the key’s value can be changed by inserting the updated value of the key. For example:

 Input:

Source: 

Output:

Source:

  • Removing Elements:

The remove() method is used to remove an element from the map. It takes the key values and removes the mapping for a key from this map if it is present. For example:

Input:

Source:

Output:

Source:

  • Traversal of a Hashtable:

An advanced “for loop” is used in Hashtable in java to iterate the table. For example:

Input:

Source: 

Output:

Source:

Programs- 

  • Program illustrating simple Hashtable in Java.

Input:

Source: 

Output:

Source: 

  • Program illustrating several of the methods supported by Hashtable in Java

Input:

Source:

Output:

Source: 

  • Program illustrating Java Hashtable Book

Input:

Source: 

Output:

Source:

  • Program illustrating Java Hashtable remove()

Input:

Source:

Output:

Source:

  • Program illustrating Java Hashtable putifAbsent()

Input:

Source:

Output:

Source 

  • Program illustrating key-value pairs using enumeration.

Input:

Source

Output:

Points to Remember- Hashtable in Java

  • It contains unique elements.
  • It contains values based on the key.
  • It is an array of a list, and each list is known as a bucket.
  • The hashcode() method is called to identify the position of the bucket.
  • The default capacity of Hashtable in java is 11 initially.
  • The loadFactor of the Hashtable class is 0.75.
  • Hashtable in java is synchronized.
  • Only non-null value can be used as a key or value.
  • It doesn’t guarantee any order.
  • The enumerator in Hashtable in java is not fail-fast.

Amid increased conversations around crypto and Blockchain technology, if you wish to educate yourself professionally on the topic, then upGrad’s Executive Post Graduate Programme in Software Development – Specialisation in Blockchain under IIIT- Bangalore is the right choice for you!

RELATED PROGRAMS