Sobes.tech
Junior — Middle

Is it possible to use null as a value for a key in a HashMap in Java?

sobes.tech AI

Answer from AI

Yes, in Java, you can use null as a key in a HashMap.

HashMap allows storing one key with a null value. The null key is handled separately since it does not have a hash code.

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, in Hashtable and some other Map implementations, using null as a key is prohibited and will lead to a NullPointerException. Therefore, it is important to consider the specific Map implementation.

Is it possible to use null as a value for a key in a… - sobes.tech