Junior — Middle
Is it possible to use null as a key in a TreeMap data structure?
sobes.tech AI
Answer from AI
In Java, the data structure TreeMap does not allow the use of null as a key. This is because TreeMap orders its keys using their natural ordering (Comparable) or by a provided comparator (Comparator).
If you try to insert a null key, a NullPointerException will be thrown when attempting to compare keys.
Example:
TreeMap<String, String> map = new TreeMap<>();
map.put(null, "value"); // will throw NullPointerException
If you need a map that allows null keys, you should use HashMap, which permits null as a key.