Sobes.tech
Junior — Middle

What restrictions exist when using null as a key in a hash table?

sobes.tech AI

Answer from AI

In Java, when using hash tables (for example, HashMap), a key can be null, but there are restrictions and features:

  • In HashMap, one null key is allowed. This is because a special handling is used for the null key, as null does not have a hashCode() method.

  • In other Map implementations, such as Hashtable, a null key is not allowed and will throw a NullPointerException.

  • When using null as a key, it is important to remember that this can complicate processing logic and lead to errors if the code does not expect such a key.

Example:

Map<String, String> map = new HashMap<>();
map.put(null, "value"); // allowed
System.out.println(map.get(null)); // will output "value"

Map<String, String> hashtable = new Hashtable<>();
hashtable.put(null, "value"); // will throw NullPointerException

Thus, using null as a key is possible but depends on the specific implementation and requires caution.

What restrictions exist when using null as a key in a… - sobes.tech