Can a `TreeMap` store `null` keys? Why or why not?
No, a TreeMap
cannot store null
keys. This is because TreeMap
uses a comparator or the natural ordering of the keys (via compareTo
) to maintain sorted order. Since null
cannot be compared, trying to insert a null
key would throw a NullPointerException
.
In contrast, HashMap
allows null
keys because it uses hash codes, which are independent of ordering.