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.
Example:
Java
// 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>(); tree_set.add( "Manish" ); tree_set.add( "Kartik" ); tree_set.add( "Anand" ); tree_set.add( "Sahil" ); // Traversing elements of TreeSet Iterator<String> it = tree_set.iterator(); while (it.hasNext()) { System.out.println(it.next()); } } } |
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
Java
// 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>(); tree_Set.add( "ABC" ); tree_Set.add( null ); // Printing TreeSet elements System.out.println(tree_Set); } } |
Output
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.
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.