Sunday, 6 October 2019

Why Does TreeSet Not Allow null Values in Java?

            TreeSet implements the Set interface and stores only unique elements, which means it does not allow duplicate values. By default, the elements in a TreeSet are stored in their natural (ascending) order. In this post, we will discuss why TreeSet does not allow null values.

Example: Adding a null Value to a TreeSet

TreeSetExample.java

package com.example.demo;

import java.util.TreeSet;

public class TreeSetExample {

         public static void main(String[] args) {

                 TreeSet<String> treeSet = new TreeSet<String>();
                  treeSet.add(null);

         }

}

Output:-
Exception in thread "main" java.lang.NullPointerException
at java.util.TreeMap.compare(Unknown Source)
at java.util.TreeMap.put(Unknown Source)
at java.util.TreeSet.add(Unknown Source)
at com.example.demo.TreeSetExample.main(TreeSetExample.java:10)


Why Doesn't TreeSet Allow null Values?

TreeSet stores its elements in sorted order. By default, it uses the natural ordering of elements, which relies on the Comparable interface and its compareTo() method. The compareTo() method compares one object with another to determine their ordering.

Since null is not an object and does not have a compareTo() method, TreeSet cannot compare a null value with other elements. As a result, attempting to add a null value to a TreeSet (using natural ordering) results in a NullPointerException.

Method declaration:

public boolean add(E e) throws ClassCastException, NullPointerException;

      In Java 6 and earlier, a TreeSet could accept null as the first element because no comparison was required when the set was empty. However, this behavior was changed in Java 7. From Java 7 onward, TreeSet does not allow null values at all when using natural ordering, and attempting to add one throws a NullPointerException.

Thank you for visiting the blog.

No comments:

Post a Comment