In this shot, we will discuss the different ways to create a HashTable
in Java.
The HashTable
class implements a hashtable, which maps keys to values. A Hashtable
is an array of a list.
Hashtable
contains values based on the key.Hashtable
contains unique elements.Hashtable
doesn’t allow null keys or values.Hashtable
is 11, whereas the loadFactor
is 0.75.The four constructors of the HashTable
class are listed below:
HashTable()
This constructs a new, empty hashtable with a default load factor of 0.75 and initial capacity of 11.
HashTable(int capacity)
This constructs a new, empty hashtable with the defined initial capacity and default load factor of 0.75.
HashTable(int capacity, float loadFactor)
This constructs a new, empty hashtable with the defined initial capacity and load factor.
HashTable(Map<? extends K,? extends V> m)
This constructs a new hashtable with the same mappings as the defined in the HashMap.
Let’s look at the code snippet.
import java.util.*;class Main{public static void main(String[] args){Hashtable<Integer, String> h1 = new Hashtable<Integer, String>();h1.put(1, "Let's");h1.put(5, "see");h1.put(2, "Hashtable");h1.put(9, "in java.");System.out.println("The Hashtable h1 is: "+h1);Hashtable<Integer, String> h2 = new Hashtable<Integer, String>(3);h2.put(1, "Let's");h2.put(55, "see");h2.put(20, "Hashtable");System.out.println("The Hashtable h2 is: "+h2);Hashtable<Integer, String> h3 = new Hashtable<Integer, String>(3,0.5f);h3.put(11, "Let's");h3.put(15, "see");h3.put(14, "Hashtable");System.out.println("The Hashtable h3 is: "+h3);Map<Integer, String> map = new HashMap<>();map.put(17, "Let's");map.put(62, "see");map.put(33, "Hashtable");Hashtable<Integer, String> h4 = new Hashtable<Integer, String>(map);System.out.println("The Hashtable h4 is: "+h4);}}
Main
class.main
function.HashTable
using the first constructor that created a HashTable
with a default initial capacity (11) and load factor (0.75) consisting of Integer
type keys and String
type values.Hashtable
by using the Hashtable.put()
method.HashTable
h1.HashTable
using the second constructor that created a HashTable
with a user defined initial capacity, i.e., 3 here, and default load factor (0.75) consisting of Integer
type keys and String
type values.Hashtable
by using the Hashtable.put()
method.HashTable
h2.HashTable
using the third constructor that created a HashTable
with a user defined initial capacity, i.e., 3 and load factor, i.e., 0.5 here, consisting of Integer
type keys and String
type values.HashTable
by using the Hashtable.put()
method.HashTable
h3.Hashmap
with Integer
type keys and String
type values.HashMap
by using the HashMap.put()
method.HashTable
using the fourth constructor that created a HashTable
with the mapping of the created HashMap
that is being passed.HashTable
h4.