C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Put: This assigns a new entry in the Hashtable. The key is the first argument. The value is the second.
Get: This looks up a value in the Hashtable from the key. Internally it computes a hash code from the key for faster searching.
Java program that uses Hashtable
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);
}
}
Output
10
Version 1: This version of the code uses the Hashtable. It checks the collection for the string key "apple."
Version 2: This code does the same thing as version 1, but uses a HashMap collection instead.
Result: The HashMap is faster, for simple lookups, by about 200%. Using HashMap when possible is an optimization.
Java program that benchmarks Hashtable, HashMap
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);
}
}
Output
53
17