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.
1 |
public Hashtable() |
The hash table object created using this constructor has the default initial capacity of 11 and the default load factor of 0.75.
1 2 3 4 5 6 |
/* * The default constructor creates a new * hashtable object with initial capacity of * 11 and load factor of 0.75 */ Hashtable<Integer, String> hashtable = new Hashtable<Integer, String>(); |
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.
1 |
public Hashtable(int initialCapacity) |
1 |
public Hashtable(int initialCapacity, float loadFactor) |
Example:
1 2 3 4 5 6 7 8 9 10 11 12 |
/* * this hash table will have the * initial capacity of 25 */ Hashtable<Integer, String> hashtable1 = new Hashtable<Integer, String>( 25 ); /* * this hash table will have the * initial capacity of 25 and the load * factor of 0.85 */ Hashtable<Integer, String> hashtable2 = new Hashtable<Integer, String>( 25, 0.85f ); |
How to copy a map object to a Hashtable object?
The Hashtable class provides an overloaded constructor that accepts a map object.
1 |
public Hashtable(Map<? extends K,? extends V> map) |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
HashMap<Integer, String> hashmap = new HashMap<Integer, String>(); hashmap.put(1, "One"); hashmap.put(2, "Two"); hashmap.put(3, "Three"); /* * To copy all mappings of HashMap to * Hashtable, use the below given constructor * and specify the map object */ Hashtable<Integer, String> hashtable = new Hashtable<Integer, String>( hashmap ); System.out.println("HashMap contains: " + hashmap); System.out.println("Hashtable contains: " + hashtable); |
Output
1 2 |
HashMap contains: {1=One, 2=Two, 3=Three} Hashtable contains: {3=Three, 2=Two, 1=One} |
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