Friday, July 19, 2024

10 Example of Hashtable in Java – Java Hashtable Tutorial

Hello Java programmers, if you are wondering how to use Hashtable class in Java then you have come to the right place. In this Java Hashtable tutorial, I am going to share how to use Hashtable in Java with examples. These Java Hashtable Examples contain some of the frequently used operations on Hashtable in Java. when I discussed throw of How HashMap or Hashtable works in Java I touched based on the inner working of Hashtable, while in this Java Hashtable tutorial we will see more examples of Hashtable in Java like checking a key exits in HashMap or not or get all keys and values from HashMap, Iterating on Hashtable keys and values using Enumeration, checking if Hashtable contains a particular key or value, how to copy mappings from a Hashtable to HashMap in Java, etc.

Even though Hashtable is an old class and a good chance that it will be deprecated in the future, you will still find lots of Hashtable based code in legacy Java applications.

So, it's important to know about this class which is another key value implementation along with HashMap, LinkedHashMap, and TreeMap but doesn't implement Map interface in Java. implementation. 

At the same time, do not write any new code using Hashtable instead use ConcurrentHashMap wherever possible. 

And, if you are wondering how Hashtable look like or how entries are stored in Hashtable, here is a simplified diagram of Hashtable in Java. 

Hashtable Examples in Java



Hashtable Examples in Java

Before using Hashtable is worth remembering that it’s an obsolete collection and there are better alternatives available in the form of HashMap and ConcurrentHashMap

You can also see the Difference between Hashtable and HashMap for comparing each other.

Examples of the Hashtable are not very different than HashMap or ConcurrentHashMap and put() and get() almost work the same except for some synchronization difference like on ConcurrentHashMap get() and put() methods can overlap but on Hashtable, they can’t because the whole map gets locked on either operation. 

On the other hand, since HashMap is not synchronized at all using it on concurrent java applications is not advised.



10 Java Hashtable Examples

Now let’s move on Hashtable examples in Java following is a list of all examples of Hashtable operation we will see in this article:

1. How to put an object into Hashtable?
You can use put() method to put a mapping of key and value in Hashtable in Java.  

Here is the code:

// Creating Hashtable for example
Hashtable companies = new Hashtable();


// Java Hashtable example to put object into Hashtable
// put(key, value) is used to insert object into map
companies.put("Google", "United States");
companies.put("Nokia", "Finland");
companies.put("Sony", "Japan");


2. How to retrieve an object from Hashtable in Java?
You can call the get() method with key object to retrieve value from Hashtable in Java. You can also use keySet() or values() or entrySet() to retrieve all keys, values, and entries from Hashtable in Java. This is similar to how you use entrySet() with HashMap class in Java. 

Here is a code example, where we are retrieving object associate with "Google" string object form our Hashtable called "companies" :

// Java Hashtable example to get Object from Hashtable
// get(key) method is used to retrieve Objects from Hashtable
companies.get("Google");


3. How to reuse Hashtable by using clear()?
Yon can use the clear() method to remove all entries or all mapping from Hashtable and then re-use it like a new Hashtable in Java. Once you call the clear() method all the associations will be removed and the size() of Hashtable will become zero. 

Here is the code:

companies.clear();




4. How to check if Hashtable contains a particular value?
You can use the containsValue() method to check if a Hashtable contains a particular value or not. If it contains the value then this method will return true otherwise it will return false.

Here is the code:

System.out.println("Does hashtable contains Japan as value: "
+ companies.containsValue("Japan"));


This will print:

Does hashtable contains Japan as value: true
because our Map contains a mapping where value is "Japan". 



5. How to check if Hashtable contains a particular key?
You can use the  containsKey() method to check if a Hashtable contains a particular key or not. If the Hashtable contains the key then it return true otherwise it will return false. 

This method is similar to containsValue() method which we have seen in the previous example.

Here is the code:

System.out.println("Does hashtable contains Google as key: "
+ companies.containsKey("Google"))

This will print:

Does hashtable contains Google as key: true

because our Hashtable contains a mapping with key as "Google".

And here is a simple diagram which shows how entries are stored in HashMap class in Java, which is quite similar to Hashtable. 


10 Example of Hashtable in Java – Java Hashtable Tutorial




6. How to traverse Hashtable in Java?
You can use Enumeration object to traverse Hashtable in Java as its a legacy class and doesn't support Iterator which we use to iterate over HashMap or ConcurrentHashMap in Java.


Here is the code example to show how to traverse through Hashtable in Java:

Enumeration enumeration = companies.elements();

while (enumeration.hasMoreElements()) {
   System.out.println("hashtable values: " + enumeration.nextElement());
}
This will print:

hashtable values: Finland
hashtable values: United States
hashtable values: Japan

Because we have 3 entries in our Hashtable. 



7. How to check if Hashtable is empty in Java?
You can call the isEmpty() method or check the size() to find out whether Hashtable in empty or not.

Here is the code:

System.out.println("Size of hashtable in Java: " + companies.size());

This will print :

Size of hashtable in Java: 3

You can see the size is 3 because we have only three mappings in our Hashtable. 

You can also use isEmpty() method as shown below:

System.out.println("Is companies hashtable empty: "
+ companies.isEmpty());
This will print:

Is companies hashtable empty: false
because our Hashtable is not empty.



8. How to Copy the content of Hashtable into HashMap?
You can copy the content of Hashtable into HashMap using different ways, for example you can enumerate over Hashtable and then add each entry into HashMap. 


9. How to find the size of Hashtable in Java?
You can take keySet() and get its size() that would be the size of Hashtable in Java. You can also use size() of Hashtable itself to find the size.


10. How to get all values from Hashtable in Java?
You can use the values() method to get all values from Hashtable.


11. How to get all keys from Hashtable in Java?
You can use keySet() method to retrieve all keys from Hashtable in Java.


Here is complete code example of all above Hashtable example or exercises:

import java.util.Collection;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Set;

public class HashtableDemo {

public static void main(String args[]) {

// Creating Hashtable for example
Hashtable companies = new Hashtable();


// Java Hashtable example to put object into Hashtable
// put(key, value) is used to insert object into map
companies.put("Google", "United States");
companies.put("Nokia", "Finland");
companies.put("Sony", "Japan");


// Java Hashtable example to get Object from Hashtable
// get(key) method is used to retrieve Objects from Hashtable
companies.get("Google");


// Hashtable containsKey Example
// Use containsKey(Object) method to check if an Object exits as key in
// hashtable
System.out.println("Does hashtable contains Google as key: "
+ companies.containsKey("Google"));


// Hashtable containsValue Example
// just like containsKey(), containsValue returns true if hashtable
// contains specified object as value
System.out.println("Does hashtable contains Japan as value: "
+ companies.containsValue("Japan"));


// Hashtable enumeration Example
// hashtabl.elements() return enumeration of all hashtable values
Enumeration enumeration = companies.elements();

while (enumeration.hasMoreElements()) {
System.out
.println("hashtable values: " + enumeration.nextElement());
}


// How to check if Hashtable is empty in Java
// use isEmpty method of hashtable to check emptiness of hashtable in
// Java
System.out.println("Is companies hashtable empty: "
+ companies.isEmpty());


// How to find size of Hashtable in Java
// use hashtable.size() method to find size of hashtable in Java
System.out.println("Size of hashtable in Java: " + companies.size());


// How to get all values form hashtable in Java
// you can use keySet() method to get a Set of all the keys of hashtable
// in Java
Set hashtableKeys = companies.keySet();


// you can also get enumeration of all keys by using method keys()
Enumeration hashtableKeysEnum = companies.keys();


// How to get all keys from hashtable in Java
// There are two ways to get all values from hash table first by using
// Enumeration and second getting values ad Collection

Enumeration hashtableValuesEnum = companies.elements();


Collection hashtableValues = companies.values();


// Hashtable clear example
// by using clear() we can reuse an existing hashtable, it clears all
// mappings.
companies.clear();
}
}


Output:
Does hashtable contains Google as key: true
Does hashtable contains Japan as value: true
hashtable values: Finland
hashtable values: United States
hashtable values: Japan
Is companies hashtable empty: false
Size of hashtable in Java: 3


That’s all on Hashtable Example in Java. We have seen almost all frequently used Hashtable operations in java. As I said earlier don’t use Hashtable as its pretty old and there are better alternatives available like ConcurrentHashMap until it’s absolutely necessary for you.


Related Java Tutorial


7 comments:

  1. Do you know how to create an hash table from scratch? I am interesting in find examples about his.

    Thanks for this information.

    ReplyDelete
  2. Why we prefer to use String as a key value not only in hashtable?

    ReplyDelete
  3. @Anonymous, There are couple of reason like String is immutable and final, they have proper equals and hashCode method etc. See my post How HashMap works in Java for more details.

    ReplyDelete
  4. How to Copy content of Hashtable into HashMap?

    ReplyDelete
  5. By default Hashtable elements are unordered how can we retreive elements same order as we put inside

    ReplyDelete
  6. At least when I try to run in Eclipse, I get the warning "Hashtable is a raw type. References to generic type Hashtable should be parameterized."
    You should declare using two reference types like this:
    Hashtable companies = new Hashtable();
    This gives you compile time errors when you try to put objects that aren't strings into your hashtable. Quite nice so you don't do something dumb like:
    companies.put("Google",909);

    ReplyDelete
  7. instead of companies.containsValue("Japan") ,
    you can write simpley companies.contains("Japan");

    ReplyDelete