HashTable in Java

In this tutorial, We will discuss the HashTable in Java.

HashTable implements the Map interface in Java. Like other Map classes, it also stores the data in a key-value pair but the HashTable store only non-null objects i.e any key or value can’t be Null.


Hashtable is similar to HashMap except it is synchronized. There are few more differences between HashMap and Hashtable class, We will discuss these in next tutorial.


Implementation of HashTable

Let’s understand the HashTable with a simple example. In this example, we are implementing the HashTable Adding the value in HashTable and performing other important operations on HashTable.


{third=THIRD Element, second=SECOND Element, first=FIRST Element}
Value of third is: THIRD Element
Value of second is: SECOND Element
Value of first is: FIRST Element


We have seen how can we insert the data in the HashTable and how can we traverse the HashTable.

Points about HashTable –

  1. HashTable is synchronized.

  2. Null is not allowed as key or value.

  3. It contains only unique elements.


Examples of HashTable

Now let’s understand the other useful operations on TreeMap.

1. Insert object into Hashtable – We can perform the insertion using put(key, value)method.

hm.put(“second”, “SECOND Element”);


2. Retrieve the object from Hashtable – get(key) method is used to retrieve Objects from Hashtable.


3. How to check a key exists in HashTable– Checking for values in treeMap in Java you can also search for keys by using method containsKey() this method will return true if you contain specified a key or return false if HashTable doesn’t contain that key.


4. How to get all values from hashtable – you can use keySet() method to get a Set of all the keys of hashtable in Java.
Set hashtableKeys = hm.keySet();


5. How to get all keys from hashtable – There are two ways to get all values from hashtable first by using Enumeration and second getting values ad Collection.

Enumeration hashtableValuesEnum = hm.elements();

Collection hashtableValues = hm.values();


6. Checking whether HashTable is empty – There is the convenient isEmpty() method from AbstactMap which is used to check whether hashtable in java is empty or not, its return true if TreeMap doesn’t contain any entry.
boolean isEmpty = hm.isEmpty();


This is how can we implement the HashTable and perform the different methods on it.


Selenium Tutorial:

If you liked this video, then please subscribe to our YouTube Channel for more video tutorials.

0 Comment

Leave a Reply