Sobes.tech
Junior — Middle

Can null values be used as keys in TreeMap?

sobes.tech AI

Answer from AI

In TreeMap, keys cannot be null because TreeMap uses the natural ordering of keys or a Comparator for sorting them. Attempting to insert null as a key will throw a NullPointerException.

This is because comparing null with other keys is impossible, and TreeMap cannot determine where to insert such a key in the sorted structure.

If you need to use null as a key, consider using HashMap, which allows one null key.

Can null values be used as keys in TreeMap? — Java - sobes.tech