Why NULL is Not Allowed in Java TreeSet?
TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided. This must be consistent with equals if it is to correctly implement the Set interface.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Anand Kartik Manish Sahil
Adding null value to TreeSet
In this example, we are going to add a NULL value in TreeSet, which is going to give us an exception
Exception in thread "main" java.lang.NullPointerException at java.base/java.util.TreeMap.put(TreeMap.java:561) at java.base/java.util.TreeSet.add(TreeSet.java:255) at Example2.main(Example2.java:10)
Explanation: By default, the Comparable interface is used internally by TreeSet to sort the elements. Now in the Comparable Interface, the compareTo() method is used to compare one value with another to sort the elements.
So because of this purpose, null has no value, that’s why the compareTo() method cannot compare null with another value, giving a NullPointerException.
add method declaration
public boolean add(E e) throws ClassCastException, NullPointerExeption;
If we try to add null values in TreeSet, it will generate a NullPointerException at the run time.