Junior — Middle
Is it possible to insert a null value into a TreeSet, and if so, under what conditions?
sobes.tech AI
Answer from AI
Inserting a null value into a TreeSet is possible but with restrictions. TreeSet is based on a red-black tree and requires elements to be comparable to maintain order.
- If TreeSet is created without a comparator, elements must implement Comparable, and inserting null will throw NullPointerException.
- If TreeSet is created with a comparator that can handle nulls, then inserting null is possible.
However, in standard Java implementation, inserting null into a TreeSet usually results in an exception because null cannot be compared with other elements.
Example:
TreeSet<String> set = new TreeSet<>();
set.add(null); // throws NullPointerException
TreeSet<String> setWithComparator = new TreeSet<>(Comparator.nullsFirst(String::compareTo));
setWithComparator.add(null); // allowed