Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Why NULL is Not Allowed in Java TreeSet?

  • Difficulty Level : Medium
  • Last Updated : 17 Dec, 2020

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.


// Java Program to illustrate the TreeSet
import java.util.*;
class GFG {
    public static void main(String args[])
        // Creating TreeSet and adding elements to it
        TreeSet<String> tree_set = new TreeSet<String>();
        // Traversing elements of TreeSet
        Iterator<String> it = tree_set.iterator();
        while (it.hasNext()) {

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


// Adding NULL value to Java TreeSet
import java.util.TreeSet;
public class Example2 {
    public static void main(String[] args)
        // Creating TreeSet and adding elements to it
        TreeSet<String> tree_Set = new TreeSet<String>();
        // Printing TreeSet elements


Exception in thread "main" java.lang.NullPointerException
    at java.base/java.util.TreeMap.put(
    at java.base/java.util.TreeSet.add(
    at Example2.main(

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.

My Personal Notes arrow_drop_up
Recommended Articles
Page :