Sobes.tech
Junior — Middle

Can HashMap contain an entry with a null key?

sobes.tech AI

Answer from AI

Yes, in Java HashMap can contain an entry with a null key. Unlike some other Map implementations, such as Hashtable, which do not allow null as a key or value, HashMap permits one null key. This is convenient when you need to store data with a missing or undefined key.

Example:

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
Can HashMap contain an entry with a null key? — Java - sobes.tech