Why TreeSet Does not allow null values in Java?


TreeSet provides an implementation of the Set interface that uses a tree for storage. Objects are stored in a sorted and ascending order.

Access and retrieval times are quite fast, which makes TreeSet an excellent choice when storing large amounts of sorted information that must be found quickly.

The reason is, if you look at the internal implementation of the TreeSet, it uses natural ordering, that means TreeSet uses Comparable interface by default to sort its value by comparing other value.

Example

public class TreeSetDemo {
   public static void main(String args[]) {
      TreeSet<String> treeSet = new TreeSet<String>();
      treeSet.add("Apple");
      treeSet.add("Mango");
      treeSet.add("Orage");
      treeSet.add("grapes");
      treeSet.add("Banana");
      System.out.println(treeSet);
   }
}

Output

[Apple, Banana, Mango, Orage, grapes]

Adding null values to a tree set

TreeSet adds elements to it according to their natural order. This internally compares the elements with each other using the compareTo (or compare) method.

If you try to compare any object with a null value using one of these methods, a NullPointerException will be thrown.

Therefore, if you try to add null values to a TreeSet it generates a NullPointerException at the run time.

Example

import java.util.Set;
import java.util.TreeSet;
public class TreeSetExample {
   public static void main(String args[]) {
      Set<Integer> treeSet = new TreeSet<Integer>();
      //Populating the HashSet
      treeSet.add(1124);
      treeSet.add(3654);
      treeSet.add(7854);
      treeSet.add(9945);
      System.out.println(treeSet);
      //Adding null elements
      treeSet.add(null);
      treeSet.add(null);
      treeSet.add(null);
      System.out.println(treeSet);
   }
}

Run time exception

Run time exception:
[1124, 3654, 7854, 9945]
Exception in thread "main" java.lang.NullPointerException
   at java.util.TreeMap.put(Unknown Source)
   at java.util.TreeSet.add(Unknown Source)
   at MyPackage.TreeSetExample.main(TreeSetExample.java:16)
raja
Published on 07-Aug-2019 15:08:16
Advertisements