Skip to content

Create New Hashtable Objects – Java Hashtable Constructors

This example shows how to create new objects of Hashtable in Java. This example also shows how to create new Hashtable objects using various hashtable constructors.

How to create new objects of Hashtable in Java?

The Hashtable class in Java provides several constructors using which we can create new hash table objects as given below.

The default hashtable constructor creates a new and empty hash table object.

The hash table object created using this constructor has the default initial capacity of 11 and the default load factor of 0.75.

The above given statement creates a hash table object whose keys are of type Integer and values are if type String.

How to specify custom initial capacity and load factor?

If you want to specify custom values for the initial capacity and load factor while creating a new object of the Hashtable class, you can use any of the below given overloaded constructors.

Example:

How to copy a map object to a Hashtable object?

The Hashtable class provides an overloaded constructor that accepts a map object.

It creates a new hash table object containing the same mappings as the specified map object. The new hash table object will have the initial capacity large enough to hold all the entries of the specified map object and the default load factor of 0.75.

The below given code shows how to convert a HashMap object to a Hashtable object using this constructor.

Output

This example is a part of the Hashtable in Java Tutorial with Examples.

Please let me know your views in the comments section below.

References:
Java 8 Hashtable Documentation

About the author

Leave a Reply

Your email address will not be published.