Java Collections – Hashtable Example
The Hashtable maps a key and a value. Hashtable has now been re-engineered to implement the Map interface and is roughly the equivalent of HashMap except that it does not permit nulls and is synchronized. In the example I have detailed, it will represent a mapping of the employee’s name and their yearly salary.
Big-O Notation
According to the Javadocs, this implementation provides constant-time O(1) performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets.
Creating a Hashtable
This was the old-way prior to Generics.
Hashtable employees = new Hashtable();
Generics
If you look closely, you will notice that I am using Generics to limit the type to String for the Key, and Integer for the Value in the Hashtable. Generics add stability to your code, by having the computer detect type incompatibilities during compile-time. These runtime bugs would be more difficult to debug if left unchecked.
Hashtable<String,Integer> employees = new Hashtable<String,Integer>();
Adding elements
Adding elements to the employees Hashtable is done by using the put(Object key, Object value) method. The key of the Hashtable will be the employee name which is a String and the value will be an Integer object. But wait? We are passing an Integer object we are passing an int primitive and Java is not complaining and we did not have to use new Integer(…). Why is this working?
Auto-Boxing and Unboxing
Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer and vice-versa without the need to cast. In this case, Java is performing the boxing when we put elements into the Hashtable (converting int to Integer wrapper class) and unboxing when we get() elements from the Hashtable (converting Integer to int primitive).
employees.put("John Smith", 85000); employees.put("David Harvey", 53000); employees.put("James Young", 103500); employees.put("Danielle Gray", 94250); employees.put("Jeff Wang", 76500); employees.put("Chris Canning", 150000); employees.put("Mary Anderson", 104100); employees.put("Tina Mayer", 143700);
Removing elements
Removing elements is just a matter of calling the remove(Object key) method.
employees.remove("Jeff Wang"); employees.remove("Mary Anderson");
Size of Collection
Returning the number of elements in a Hashtable is as easy as calling the size() method.
employees.size();
Iterating through the Collection
Java 1.5 and above provides a foreach loop, which makes it much easier to iterate over the entire collection. This is my preferred way of doing it.
// Loop through the collection of employees for (String name : employees.keySet()) { // Get the salary by passing the employee name as the key,
the salary is Auto-UnBoxed int salary = employees.get(name); }
Iterating through the Collection with Generics
Hashtable<String,Integer> employees = new Hashtable<String,Integer>(); Iterator iterator = employees.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String,Integer> element = (Map.Entry) iterator.next(); String name = element.getKey(); int salary = element.getValue(); System.out.format("Employee==> %-14s | %8dn", name, salary); }
Iterating through the Collection without Generics
Hashtable employees = new Hashtable(); Iterator iterator = employees.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry element = (Map.Entry) iterator.next(); String name = (String) element.getKey(); int salary = ((Integer)element.getValue()).intValue(); System.out.format("Employee==> %-14s | %8dn", name, salary); }
Please Note
Using a Hashtable does not guarantee the order of the elements.
Full Program Listing
package com.avaldes.tutorials; import java.util.Hashtable; import java.util.Map; public class HashTableExample { public static void main(String[] args) { // Ensure that the Hashtable only takes String for the key and Integer for the value Hashtable<String,Integer> employees = new Hashtable<String,Integer>(); // Populate the employee Hashtable -- Auto-Boxing employees.put("John Smith", 85000); employees.put("David Harvey", 53000); employees.put("James Young", 103500); employees.put("Danielle Gray", 94250); employees.put("Jeff Wang", 76500); employees.put("Chris Canning", 150000); employees.put("Mary Anderson", 104100); employees.put("Tina Mayer", 143700); System.out.println("Display All Employees -- prior to delete operation..."); displayAllEmployees(employees); System.out.println("Number of Employees: " + employees.size()); // See if someone with name 'James Young' is in the employees hashtable System.out.println("nCheck to see if James Young is found in employees instance: " + employees.containsKey("James Young")); // See if someone with name 'Amaury Valdes' is in the employees hashtable System.out.println("Check to see if Amaury Valdes is found in employees instance: " + employees.containsKey("Amaury Valdes")); // Is employees instance empty? System.out.println("Check to see if employees instance is empty: " + employees.isEmpty()); // Let's remove employee Jeff Wang & Mary Anderson System.out.println("nRemoving Jeff Wang from employees"); employees.remove("Jeff Wang"); System.out.println("Removing Mary Anderson from employeesn"); employees.remove("Mary Anderson"); System.out.println("Display All Employees -- after delete operation..."); displayAllEmployees(employees); System.out.println("Number of Employees: " + employees.size()); } static public void displayAllEmployees(Hashtable<String,Integer> employees) { int count = 0; // Loop through the collection of employees for (String name : employees.keySet()) { count++; // Get the salary by passing the employee name as the key, the salary is Auto-UnBoxed int salary = employees.get(name); // Format the output nicely System.out.format("Employee==> [%d] %-14s | %8dn", count, name, salary); } } }
Output
Display All Employees -- prior to delete operation... Employee==> [1] Jeff Wang | 76500 Employee==> [2] Mary Anderson | 104100 Employee==> [3] James Young | 103500 Employee==> [4] Tina Mayer | 143700 Employee==> [5] John Smith | 85000 Employee==> [6] David Harvey | 53000 Employee==> [7] Chris Canning | 150000 Employee==> [8] Danielle Gray | 94250 Number of Employees: 8 Check to see if James Young is found in employees instance: true Check to see if Amaury Valdes is found in employees instance: false Check to see if employees instance is empty: false Removing Jeff Wang from employees Removing Mary Anderson from employees Display All Employees -- after delete operation... Employee==> [1] James Young | 103500 Employee==> [2] Tina Mayer | 143700 Employee==> [3] John Smith | 85000 Employee==> [4] David Harvey | 53000 Employee==> [5] Chris Canning | 150000 Employee==> [6] Danielle Gray | 94250 Number of Employees: 6
Other Related Posts
Map Examples
- Hashtable Example
Simple example shows you step by step how to use Hashtable - HashMap Example
Simple example shows you step by step how to use HashMap - TreeMap Example
Simple example shows you step by step how to use TreeMap to sort a collection - EnumMap Example
Simple example shows you step by step how to use EnumMap for type-safety and speed of finite list of elements - WeakHashMap Example
Simple example shows you step by step how to use WeakHashMap - LinkedHashMap Example
Simple example shows you step by step how to use LinkedHashMap - Performance Comparison HashMap vs Hashtable vs TreeMap
Performance Comparison - Performance Comparison HashMap vs Hashtable vs TreeMap Benchmark Test
List Examples
- Stack Example
Simple example shows you step by step how to use Stack - Vector Example
Simple example shows you step by step how to use Vector - LinkedList Example
Simple example shows you step by step how to use LinkedList - ArrayList Example
Simple example shows you step by step how to use ArrayList - Performance Comparison between the four list implementations
Performance Comparison of ArrayList, LinkedList, Vector, and Stack - Performance Comparison ArrayList vs LinkedList
Performance Comparison - ArrayList vs LinkedList
Set Examples
- BitSet Example
Simple example shows you step by step how to use BitSet - EnumSet Example
Simple example shows you step by step how to use EnumSet - HashSet Example
Simple example shows you step by step how to use HashSet - TreeSet Example
Simple example shows you step by step how to use TreeSet - LinkedHashSet Example
Simple example shows you step by step how to use LinkedHashSet
Leave a Reply