Let’s begin with the similarities of HashMap and HashTable:
- Both store key and value pairs in a hash table
- Both declare an object which are both declared as a key
- The key is hashed, and then this hash is indexed within the hash table it is stored
HashMap vs HashTable
HashMap
- None-synchronised. Not thread safe, unable to be shared between other threads.
- Allows for one null key and multiple null values
- Preferred if thread synchronisation is not needed
- Performance is high as threads are not required to wait
- Introduced in 1.2
- None legacy
- Not good for multithreaded environments
HashTable
- Synchronised. Thread safe, can be shared between other threads.
- Does not allow for null values in key or value
- Preferred if synchronisation is needed
- Performance is impacted as waiting for threads
- Introduced in 1.0
- Legacy
- Good for multithreaded environments
HashMap Example
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("apple", 5);
map.put("banana", 3);
map.put("orange", 10);
int value = map.get("banana");
System.out.println(value); // Output: 3
map.remove("orange");
map.put("orange", 8);
System.out.println(map); // Output: {apple=5, banana=3, orange=8}
}
}
HashTable Example
import java.util.Hashtable;
public class HashTableExample {
public static void main(String[] args) {
Hashtable<String, Integer> table = new Hashtable<>();
table.put("apple", 5);
table.put("banana", 3);
table.put("orange", 10);
int value = table.get("banana");
System.out.println(value); // Output: 3
table.remove("orange");
table.put("orange", 8);
System.out.println(table); // Output: {apple=5, banana=3, orange=8}
}
}