718 views
Is it possible to use null as a key in a HashMap in Java?
Asked at
AI answer
In Java, the HashMap class allows using null as a key. Specifically, HashMap permits exactly one key with the value null.
This is possible because when computing the hash code for a null key, a special handling is used — instead of calling hashCode(), it returns 0.
Example:
import java.util.HashMap;
public class Example {
public static void main(String[] args) {
HashMap<String, String> map = new HashMap<>();
map.put(null, "value for null key");
System.out.println(map.get(null)); // Will output: value for null key
}
}
However, it is important to remember that other Map implementations, such as Hashtable, do not allow null as a key or value.
Also asked at Иннотех
- Tell about your work experience, what projects you participated in, what tasks you performed.
- Do you have any questions about the project?
- What database management systems have you already worked with?
- An HTTP request—can you name its components?
- Tell me about the principles of object-oriented programming.