A Hashtable in Java is a data structure that stores data in key-value pairs. It’s like a dictionary you use a key to find a value.
Example:
hashtable.put("name", "John");
Now you can get the value “John” by using the key “name”.
Now, Why No Null Keys or Values?
Java’s Hashtable does not allow null as a key or value, and here’s why — in simple terms:
1. Key Uses .equals() and .hashCode()
To find where to store or look up a key, the Hashtable uses:
- hashCode() to decide where to store the value
- equals() to check which key you mean
But if the key is null, calling hashCode() or equals() on it will cause a NullPointerException which is an error.
To avoid this error, Hashtable simply doesn’t allow null keys.
2. Null Values Can Cause Confusion
When you try to get a value:
String value = hashtable.get("name");
If the value is null, it’s not clear whether:
- The key “name” was never added, or
- The key exists but its value is null
To avoid this confusion, Hashtable also doesn’t allow null values.
3. Safety and Design Choice
When Java’s Hashtable was created, the goal was to make it safe and strict — especially for multi-threaded programs.
So, the designers made it reject nulls to prevent hidden bugs and crashes.
So, Hashtable doesn’t allow null keys or null values to keep things safe and clear.
The newer class HashMap (which is more flexible) does allow:
- One null key
- Multiple null values
So if you need that behavior, you can use HashMap instead of Hashtable.