1. Overview
In this article, we will see whether the Java TreeSet class does not allow null value. A TreeSet
extends AbstractSet
and implements the NavigableSet
interface.
To learn about Java collections, refer to this article.
2. Java TreeSet class
A TreeSet creates a collection that uses a tree for storage. It stores the elements in sorted, ascending order and prevents any duplicates. Access and retrieval times are quite fast, which makes the TreeSet an excellent choice when storing large amounts of sorted information that must be retrieved quickly.
It works just like the Collections.sort
method.
A TreeSet is similar to HashSet in that:
- Prevents duplicates
- Keeps the list sorted automatically
- Does not accept null values
The downside to TreeSet
is that if you don’t need sorting, you’re still paying for it with a small performance hit. But you’ll probably find that the hit is almost impossible to notice for most apps.
2.1. Java TreeSet class sorting order
By default, the TreeSet uses each object’s compareTo
method for the sort. But you have the option of passing a Comparator
to the TreeSet
constructor, to have the TreeSet use that instead.
To use a TreeSet
, one of these things must be true:
- The elements in the list must be of a type that implements
Comparable
. - Specify the comparator as an argument to the TreeSet’s overloaded constructor
3. TreeSet class does not allow null value
As mentioned earlier, a TreeSet cannot accept null values.
@Test void treeSetWithNullExample() { TreeSet<String> treeSet = new TreeSet<String>(); treeSet.add("Z"); treeSet.add(null); }
By default, the Comparable interface is used internally by the 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.
java.lang.NullPointerException at java.base/java.util.Objects.requireNonNull(Objects.java:208) at java.base/java.util.TreeMap.put(TreeMap.java:801) at java.base/java.util.TreeMap.put(TreeMap.java:534) at java.base/java.util.TreeSet.add(TreeSet.java:255)
However, you can change this behavior by using a custom comparator that handles the null
values. Once you handle null
in the comparator, the TreeSet
won’t throw NullPointerException
.
@Test void treeSetWithNullExample() { TreeSet<String> treeSet = new TreeSet<String>(new Comparator<String>() { @Override public int compare(String o1, String o2) { if (o1 == null) return 1; if (o2 == null) return -1; return o1.compareTo(o2); } }); treeSet.add("Z"); treeSet.add(null); System.out.println(treeSet); }
If you execute the above test case, it shows the following output.
[Z, null]
4. Conclusion
To sum up, we have learned that the TreeSet class does not allow a null value and a solution to make it allow. You can find code samples in our GitHub repository.