Hashtable
This is an associative array: it associates keys (of any type) to values (of any type). HashMap
is similar to Hashtable
but not thread safe. It is slower.
With Hashtable
, performance is reduced by internal synchronization (thread-checking) code. This makes it about 200% slower than HashMap
on simple lookups (with containsKey
).
This program shows how to create a new Hashtable
with String
keys, Integer values. We can use any class
type for the keys and values. We use put and get.
Put()
assigns a new entry in the Hashtable
. The key is the first argument. The value is the second.Get()
looks up a value in the Hashtable
from the key. Internally it computes a hash code from the key for faster searching.import java.util.Hashtable; public class Program { public static void main(String[] args) { // Create Hashtable and add two entries. Hashtable<String, Integer> hash = new Hashtable<>(); hash.put("cat", 10); hash.put("dog", 15); // Get value at this key. int value = hash.get("cat"); System.out.println(value); } }10
Hashtable
This program benchmarks the Hashtable
against HashMap
. We first initialize the 2 collections with put()
method calls.
Hashtable
. It checks the collection for the string
key "apple."HashMap
collection instead.HashMap
is faster, for simple lookups, by about 200%. Using HashMap
when possible is an optimization.import java.util.HashMap; import java.util.Hashtable; public class Program { public static void main(String[] args) throws Exception { Hashtable<String, Integer> table = new Hashtable<>(); table.put("carrot", 10); table.put("apple", 20); HashMap<String, Integer> map = new HashMap<>(); map.put("carrot", 10); map.put("apple", 20); long t1 = System.currentTimeMillis(); // Version 1: check Hashtable. for (int i = 0; i < 1000000; i++) { if (!table.containsKey("apple")) { throw new Exception(); } } long t2 = System.currentTimeMillis(); // Version 2: check HashMap. for (int i = 0; i < 1000000; i++) { if (!map.containsKey("apple")) { throw new Exception(); } } long t3 = System.currentTimeMillis(); // ... Times. System.out.println(t2 - t1); System.out.println(t3 - t2); } }53 17
In most programs, a HashMap
is the better choice. If we have complex threading requirements, Hashtable
may be necessary. HashMap
has a significant performance advantage.
Over the years, Hashtable
has been retrofitted to support modern interfaces and generics in Java. And HashMap
was introduced to provide an entirely new, faster option.